0
0
Linux-cliHow-ToBeginner · 3 min read

How to Use tr Command in Linux: Syntax and Examples

The tr command in Linux is used to translate or delete characters from input text. You use it by specifying sets of characters to replace or remove, like tr 'a-z' 'A-Z' to convert lowercase letters to uppercase.
📐

Syntax

The basic syntax of the tr command is:

  • tr [options] SET1 [SET2]

Here, SET1 is the set of characters to translate or delete, and SET2 is the set of characters to translate to. If SET2 is omitted, tr deletes characters from SET1 if the -d option is used.

Common options include:

  • -d: delete characters in SET1
  • -s: squeeze repeated characters into one
  • -c: complement the set of characters in SET1
bash
tr [options] SET1 [SET2]
💻

Example

This example converts all lowercase letters in the input to uppercase using tr. It reads from standard input and outputs the converted text.

bash
echo "hello world" | tr 'a-z' 'A-Z'
Output
HELLO WORLD
⚠️

Common Pitfalls

One common mistake is forgetting that tr works only with single characters, not strings. For example, tr 'abc' 'xyz' replaces each character a, b, or c with x, y, or z respectively, but it does not replace the string "abc" as a whole.

Another pitfall is not using quotes around sets, which can cause shell interpretation issues.

bash
echo "abcabc" | tr 'abc' 'xyz'
# Output: xyzxyz

echo "abcabc" | tr "abc" "xyz"
# Output: xyzxyz
Output
xyzxyz xyzxyz
📊

Quick Reference

OptionDescription
-dDelete characters in SET1
-sSqueeze repeated characters into one
-cComplement the characters in SET1
SET1Characters to translate or delete
SET2Characters to translate to

Key Takeaways

Use tr 'a-z' 'A-Z' to convert lowercase to uppercase letters.
The -d option deletes characters from input.
Always quote character sets to avoid shell issues.
tr works on single characters, not strings.
Combine options like -s to squeeze repeated characters.