Linux commands
Browse topics

Selecting and translating text with cut and tr

Version
unversioned
Review
Draft

Summary#

cut selects bytes, characters or delimited fields from each line. tr translates, squeezes or deletes characters read from standard input.

Syntax#

sh
cut -d: -f1,3 file
tr -s ' ' < file
tr -d '\r' < file
tr '[:lower:]' '[:upper:]' < file

Example#

sh
(
  set -eu
  export LC_ALL=C
  dir=$(mktemp -d)
  trap 'rm -rf -- "$dir"' EXIT
  cd "$dir"
  printf 'ana:x:1001:/home/ana\nbinh:x:1002:/home/binh\n' > users.txt

  cut -d: -f1,3 users.txt
  echo '-- asking for 3,1 keeps the input order'
  cut -d: -f3,1 users.txt
  echo '-- repeated spaces create empty fields'
  line='web    running    80'
  printf 'before: [%s]\n' "$(printf '%s\n' "$line" | cut -d' ' -f2)"
  printf 'after: [%s]\n' "$(printf '%s\n' "$line" | tr -s ' ' | cut -d' ' -f2)"
  echo '-- delete carriage returns and uppercase'
  printf 'release\r\n' | tr -d '\r' | tr '[:lower:]' '[:upper:]'
)

Expected output#

Text
ana:1001
binh:1002
-- asking for 3,1 keeps the input order
ana:1001
binh:1002
-- repeated spaces create empty fields
before: []
after: [running]
-- delete carriage returns and uppercase
RELEASE

Common mistakes#

cut treats every delimiter as a field boundary, so squeeze repeated spaces with tr -s ' ' first, or use awk. Lines without the delimiter pass through whole unless you add -s. tr maps individual characters rather than words, and GNU tr fully supports only single-byte locales, so do not use it to translate multibyte UTF-8 letters.

Version applicability#

This entry describes GNU coreutils cut and tr. GNU cut gained multibyte character selection with -c in coreutils 9.11. In earlier upstream releases, including GNU coreutils 9.7 on Ubuntu 26.04, -c selects bytes.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0