Skip to main content

tr is a command in Unix-like operating systems. It is an abbreviation of translate or transliterate, indicating its operation of replacing or removing specific characters in its input data set.
The utility reads a byte stream from its standard input and writes the result to the standard output. As arguments, it takes two sets of characters (generally of the same length), and replaces occurrences of the characters in the first set with the corresponding elements from the second set.

#replace : with new line
echo $PATH|tr ":" "\n" #equivalent with:
echo $PATH|tr -t ":" \n

#remove all occurance of "ab"
echo aabbcc |tr -d "ab"
#ouput: cc

#complement "aa"
echo aabbccd |tr -c "aa" 1
#output: aa11111 without new line
#tip: Complement meaning keep aa,all others are replaced with 1

#complement "ab\n"
echo aabbccd |tr -c "ab\n" 1
#output: aabb111 with new line

#Preserve all alpha(-c). ":-[:digit:] etc" will be translated to "\n". sequeeze mode.
echo $PATH|tr -cs "[:alpha:]" "\n"

#ordered list to unordered list
echo "1. /usr/bin\n2. /bin" |tr -cs " /[:alpha:]\n" "+"

# ---

# To replace all occurrences of a character in a file, and print the result:
tr <find_character> <replace_character> < <filename>

# To replace all occurrences of a character from another command's output:
echo <text> | tr <find_character> <replace_character>

# To map each character of the first set to the corresponding character of the second set:
tr '<abcd>' '<jkmn>' < <filename>

# To delete all occurrences of the specified set of characters from the input:
tr -d '<input_characters>' < <filename>

# To compress a series of identical characters to a single character:
tr -s '<input_characters>' < <filename>

# To translate the contents of a file to upper-case:
tr "[:lower:]" "[:upper:]" < <filename>

# To strip out non-printable characters from a file:
tr -cd "[:print:]" < <filename>