tr Command Cheat Sheet
tr (translate) copies standard input to standard output, performing substitution or deletion of selected characters.
Input Source: tr ONLY processes Stdin. It does not accept filenames as arguments (use < or pipes).
Synopsis
tr [OPTION]... SET1 [SET2]
Basic Translation
Lowercase to Uppercase
echo "hello world" | tr 'a-z' 'A-Z'
# Output: HELLO WORLD
Replace Characters
Replace spaces with underscores.
echo "Hello World" | tr ' ' '_'
# Output: Hello_World
Swap Characters
echo "{ok}" | tr '{}' '()'
# Output: (ok)
Deletion (-d)
Delete specific characters.
# Remove all digits
echo "User123" | tr -d '0-9'
# Output: User
# Remove newlines (join lines)
cat file.txt | tr -d '\n'
Squeeze Repeats (-s)
Replace a sequence of repeated characters with a single occurrence.
# Fix extra spaces
echo "Too many spaces" | tr -s ' '
# Output: Too many spaces
Delete & Squeeze
Delete digits AND squeeze spaces.
echo "Item 123 Price" | tr -d '0-9' | tr -s ' '
Complement (-c)
Operate on everything except the specified set.
# Keep only alphanumeric and newlines (delete everything else)
cat file.txt | tr -cd '[:alnum:]\n'
ROT13 Encryption (Caesar Cipher)
Shift characters by 13 positions.
alias rot13="tr 'A-Za-z' 'N-ZA-Mn-za-m'"
echo "secret" | rot13
# Output: frperg
Character Classes
[:alnum:]: Letters and digits[:alpha:]: Letters[:digit:]: Digits[:punct:]: Punctuation[:space:]: Whitespace (tab, newline, vertical tab, form feed, return, space)[:upper:]: Uppercase[:lower:]: Lowercase
# Remove all punctuation
cat text.txt | tr -d '[:punct:]'