Bash tr Command - Translate or Delete Characters
Using the tr Command
The tr (translate) command replaces characters with other characters. It can also delete characters, or squeeze repeated ones into one.
tr only reads from input, so you send text to it with a pipe or with <.
Replace Characters
Give tr two sets of characters. Each character in the first set is replaced by the character in the same place in the second set:
Here, e became i and every l became p.
Change Upper and Lower Case
Use ranges like a-z and A-Z to change the case of text:
You can also use the named classes [:lower:] and [:upper:]:
Example: Convert to Lower Case
echo "Hello World" | tr "[:upper:]" "[:lower:]"
hello world
Delete Characters (-d)
Use -d to delete every character in the set:
Squeeze Repeated Characters (-s)
Use -s to replace a run of the same character with just one:
One Word per Line
A common trick is to replace spaces with new lines (\n), to put each word on its own line:
Example: Split Words onto Lines
echo "red green blue" | tr " " "\n"
red
green
blue
Options Overview
tr SET1 SET2: Replace characters in SET1 with those in SET2-d: Delete characters-s: Squeeze repeated characters into one-c: Use every character that is NOT in the set