0
0
Linux CLIscripting~5 mins

tr (translate characters) in Linux CLI - Commands & Configuration

Choose your learning style9 modes available
Introduction
Sometimes you need to change or remove certain characters in text. The tr command helps you replace or delete characters quickly in Linux command line.
When you want to convert all lowercase letters in a file to uppercase.
When you need to remove all digits from a text stream.
When you want to replace spaces with underscores in filenames.
When cleaning up input by deleting unwanted characters like punctuation.
When preparing data by translating characters before processing.
Commands
This command converts all lowercase letters in the phrase 'hello world' to uppercase letters.
Terminal
echo "hello world" | tr 'a-z' 'A-Z'
Expected OutputExpected
HELLO WORLD
This command deletes all digits from the string 'user1234data', leaving only letters.
Terminal
echo "user1234data" | tr -d '0-9'
Expected OutputExpected
userdata
-d - Deletes characters specified in the set.
This command replaces all spaces in the filename with underscores to make it easier to handle in scripts.
Terminal
echo "file name with spaces.txt" | tr ' ' '_'
Expected OutputExpected
file_name_with_spaces.txt
Key Concept

If you remember nothing else from tr, remember: it replaces or deletes characters from input streams one by one.

Common Mistakes
Using tr with strings of different lengths for source and target sets.
tr expects the source and target sets to be the same length for translation; otherwise, it may produce unexpected results.
Make sure the sets you provide to tr have the same number of characters when translating.
Trying to use tr to replace words or multiple characters at once.
tr works on single characters only, not strings or words.
Use other tools like sed or awk for replacing words or patterns.
Not quoting character sets, causing shell expansion issues.
Without quotes, the shell might interpret characters like * or ? before tr runs.
Always quote character sets to prevent shell expansion.
Summary
Use tr to translate or delete characters in text streams.
The -d flag deletes specified characters instead of replacing them.
Always ensure source and target character sets are the same length for translation.