What it does
tr (translate) works on characters, not words. It reads standard input only (no file names), so you use it in a pipe or with <.
Typical jobs: change lower case to upper case, change one separator to another, remove characters (like Windows \r), or squeeze repeated spaces into one.
How to write it
tr [OPTION]... SET1 [SET2]Options 12
Most used
Sets
Nothing matches this filter.
Examples 11
$ run as a normal user# run as root (or with sudo)
1Lower case to upper case
echo "server1" | tr 'a-z' 'A-Z' SERVER1Same as
tr '[:lower:]' '[:upper:]'.2Remove Windows line endings
tr -d '\r' < script-from-windows.sh > script.shFixes "bad interpreter: No such file or directory".
3Squeeze many spaces into one
After squeezing,
cutcan use the space as separator.4The PATH one folder per line
echo "$PATH" | tr ':' '\n'Easy to read.
5Remove all digits
echo "abc123def" | tr -d '0-9' abcdefDelete a set of characters.
6Keep only letters and digits
echo "us3r_n@me!" | tr -cd '[:alnum:]' us3rnme-c= everything else,-d= delete it.7Make a random password
20 random letters and digits.
8Split words into lines
echo "one two three" | tr ' ' '\n'Then
sort | uniq -ccan count words.9Convert a CSV to TAB separated
tr ',' '\t' < data.csv > data.tsvSimple files only (no quoted commas).
10Change a hostname to a valid label
echo "Web Server 01" | tr '[:upper:] ' '[:lower:]-' web-server-01Spaces become dashes, letters become lower case.
11Read NUL-separated data
tr '\0' '\n' < /proc/1/cmdline/proc files separate words with NUL bytes.
Nothing matches this filter.
Watch out
- tr does not read file names: use
tr … < file. - tr changes single characters, not words. For words use
sed.
Tips to remember
tr -ddelete,tr -ssqueeze,tr 'a-z' 'A-Z'upper case.