0
0
Bash-scriptingHow-ToBeginner · 3 min read

How to Use tr Command in Bash for Text Transformation

In bash, tr is a command-line utility used to translate or delete characters from input text. You use it by piping text into tr followed by sets of characters to replace or remove, like echo "text" | tr 'a-z' 'A-Z' to convert lowercase to uppercase.
📐

Syntax

The basic syntax of tr 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 with the -d option, characters in SET1 are deleted.

bash
tr [options] SET1 [SET2]
💻

Example

This example converts all lowercase letters to uppercase using tr. It shows how to pipe text into tr and transform it.

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

Common Pitfalls

Common mistakes include:

  • Not quoting character sets, which can cause shell expansion issues.
  • Using tr without piping or redirecting input, so it waits for manual input.
  • Trying to translate sets of different lengths without understanding how tr handles them.

Always quote sets and provide input via pipe or file redirection.

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

# Wrong: no input given, tr waits for manual input
tr 'a-z' 'A-Z'

# Right: use echo or cat to provide input
cat file.txt | tr 'a-z' 'A-Z'
Output
HELLO
📊

Quick Reference

OptionDescriptionExample
-dDelete characters in SET1echo "abc123" | tr -d '0-9' # Output: abc
-sSqueeze repeated charactersecho "aaabbb" | tr -s 'a' # Output: abbb
-cComplement SET1echo "abc" | tr -cd 'a-c' # Output: abc

Key Takeaways

Use tr to translate, delete, or squeeze characters in text streams.
Always provide input to tr via pipe or file redirection; it does not take filenames as arguments.
Quote character sets to avoid shell interpretation issues.
Use options like -d to delete and -s to squeeze repeated characters.
Remember tr works on single characters, not strings or words.