tr (translate abbreviation) is mainly used to delete control characters in files or perform character conversion.
Syntax: tr [–c/d/s/t] [SET1] [SET2] #SET1: Character Set 1; SET2: Character Set 2
-c:complement, replace characters other than SET1 with SET2.
-d: delete, delete all characters in SET1, without conversion.
-s:squeeze-repeats, compressing duplicate characters in SET1.
-t: truncate-set1, convert SET1 with SET2, generally default is -t.
1. Remove duplicate characters
#Deleting blank lines means deleting newlines/n.
#Note: There are only carriage return characters on these blank lines, no space characters.
$ cat
I love linux!
Hello World!
Shell is worthy to been studied.
#The escape characters with newlines are used here\n.
#Note: The redundant newline characters are deleted with -s. If -d is used, all newline characters will be deleted.
$ cat | tr -s ["\n"]
I love linux!
Hello World!
Shell is worthy to been studied.
#You can also use the octal characters \012, and \012 and \n are both newline characters.
$ cat | tr -s "[\012]"
I love linux!
Hello World!
Shell is worthy to been studied.
2. Case swap
# Turn all lowercase letters in the statement into uppercase letters, where -t can be omitted.
$ echo "Hello World I Love You" |tr [-t] [a-z] [A-Z]
HELLO WORLD I LOVE YOU
# Turn all uppercase letters in the statement into lowercase letters.
$ echo "Hello World I Love You" |tr [A-Z] [a-z]
hello world i love you
# You can also use character classes for conversion.
# [:lower:] represents lowercase letters, [:upper:] represents uppercase letters.
$ echo "Hello World I Love You" |tr [:lower:] [:upper:]
HELLO WORLD I LOVE YOU
3. Delete the specified character
$ cat
Monday 09:00
Tuesday 09:10
Wednesday 10:11
Thursday 11:30
Friday 08:00
Saturday 07:40
Sunday 10:00
# Now you want to delete all characters outside of the week.
# -d represents deletion, [0-9] represents all numbers, [: ] represents colons and spaces.
$ cat | tr -d "[0-9][: ]"
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
4. Use -c to replace the complement
# Sometimes in the text we only know some characters to keep, and there are many other characters, so we can use the replacement of the complement.
$ cat
Monday 09:00
Tuesday 09:10
Wednesday 10:11
Thursday 11:30
Friday 08:00
Saturday 07:40
Sunday 10:00
# We only need weeks, and the idea is to replace everything except the letters.
# Here, -c: Replace all characters except letters with newlines; -s: Remove excess newlines.
$ cat |tr -cs "[a-z][A-Z]" "\n"
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
Summary: It is more commonly used to convert upper and lower case letters and delete unnecessary characters. The tr syntax is simple and easy to use.