Linux tr Command: Translate and Delete Characters
tr replaces or deletes characters from standard input and compresses repeated characters. First, remember that it does not take file names as arguments directly.
What is the tr command?
tr is a character-level filter. To find string patterns and replace them contextually, sed is more suitable. Since the interpretation of character ranges can be affected by locale, check the input character set in scripts.
Basic syntax
tr [OPTION] SET1 [SET2] < INPUTFILE
Installed implementations and options may vary depending on the distribution. Use man tr to check the description on your current system.
Examples
Lowercase to uppercase
Pass input through a pipe and display the results on the screen.
printf '%s\n' hello | tr '[:lower:]' '[:upper:]'
Delete specific characters
-d removes characters that belong to the specified character set.
tr -d '\r' < windows-lines.txt
Repeat Space Compression
Reduces consecutive space characters to one. A separate substitution is required to unify tabs and spaces into one type.
tr -s ' ' < notes.txt
Character-level conversion result
tr replaces or deletes characters from standard input one by one. The following is an example of changing uppercase English letters to lowercase.
printf 'HELLO 123\n' | tr '[:upper:]' '[:lower:]'
Example output:
hello 123
Numbers and spaces are not subject to conversion, so they remain unchanged. Since tr does not take a file path argument, when processing files, use redirection like tr... < original > result. For complex replacements of multi-byte characters or word/regex replacements, sed or other text processing tools are more suitable.
Main Options and Format
| Options/Format | Description |
|---|---|
-d |
Deletes characters corresponding to set1. |
-s |
Compresses repeated occurrences of the corresponding character to one. |
-c |
Selects characters that are not in set1. |
[:lower:] / [:upper:] |
Represents uppercase and lowercase sets with a character class. |
Precautions when using
Does not modify the input file. tr ... < file > file may cause the shell to empty the file first, so use a separate output file. The sets in tr are not full regular expressions, and check implementation and locale limitations for UTF-8 multibyte handling.
Frequently Asked Questions
Can you put a file name like tr file.txt?
No. The content of the file must be provided to standard input like tr... < file.txt.
Official Documentation
The exact behavior of the options and implementation differences can be found in the official tr documentation.









