$linuxjunkies
>

tr(1)

Translate or delete characters from input text.

UbuntuDebianFedoraArch

Synopsis

tr [OPTION]... SET1 [SET2]

Description

The tr command reads from standard input and writes to standard output, translating each character in SET1 to the corresponding character in SET2, or deleting characters in SET1 when SET2 is omitted. It is commonly used for character substitution, case conversion, and character deletion.

Character sets can include individual characters, ranges (e.g., a-z), escape sequences (e.g., \n for newline), and special designators like [:lower:], [:upper:], [:digit:], [:space:], and [:alnum:].

Common options

FlagWhat it does
-d, --deleteDelete characters in SET1; do not translate
-s, --squeeze-repeatsReplace each sequence of repeated characters in SET1 with a single character
-c, --complementUse the complement of SET1 (all characters except those in SET1)
-t, --truncate-set1Truncate SET1 to the length of SET2 before processing

Examples

Convert lowercase to uppercase

echo 'hello world' | tr 'a-z' 'A-Z'

Convert uppercase to lowercase

echo 'HELLO WORLD' | tr 'A-Z' 'a-z'

Delete all spaces from the text

echo 'hello world' | tr -d ' '

Squeeze repeated characters to single occurrence

echo 'aabbccdd' | tr -s 'abcd'

Replace hyphens with forward slashes

echo '2024-01-15' | tr '-' '/'

Extract only digits from the text

echo 'hello123world' | tr -cd '0-9'

Convert newlines to spaces, joining all lines

cat file.txt | tr '\n' ' '

Use character classes to convert to uppercase

echo 'test' | tr '[:lower:]' '[:upper:]'

Related commands