The TR (translate abbreviation) is primarily used to remove control characters from a file, or to convert characters.
Syntax: TR [–c/d/s/t] [SET1] [SET2]
SET1: Character Set 1
SET2: Character Set 2
-c:complement, replacing characters that are not contained in SET1 with SET2
-d:delete, delete all characters in SET1, do not convert
-s:squeeze-repeats, compressing repeated characters in a SET1
-t:truncate-set1, convert SET1 with SET2, usually the default is-t
1. Remove duplicate characters
#将连续的几个相同字符压缩为一个字符
$ echo aaacccddd | Tr-s [A-z]
Acd
$ echo aaacccddd | tr-s [ABC]
Acddd
2. Delete blank lines
#删除空白行就是删除换行符/N
#注意: There are only carriage returns on these blank lines, no whitespace
$ cat Test.txt
I Love linux!
Hello world!
Shell is worthy to been studied
#这里用换行符的转义字符 \ n
#注意: The extra line break is removed here with-s and all newline characters are removed if you use-D
$ Cat Test.txt | tr-s ["\ n"]
I Love linux!
Hello world!
Shell is worthy to been studied
#也可以用八进制符 \012,\012 and \ n are newline characters.
$ Cat Test.txt | Tr-s "[\012]"
I Love linux!
Hello world!
Shell is worthy to been studied
3, the case of conversion to each other
#将语句中所有的小写字母变成大写字母, where-t can be omitted
$ echo "Hello World I Love You" |tr [-t] [A-z] [a-z]
HELLO World I Love You
#将语句中所有的大写字母变成小写字母
$ echo "Hello World I Love You" |tr [A-z] [a-z]
Hello World I Love You
#也可以利用字符类进行转换
#[:lower:] stands for lowercase letters, [: Upper:] for uppercase letters
$ echo "Hello World I Love You" |tr [: Lower:] [: Upper:]
HELLO World I Love You
4. Delete the specified character
$ cat Test.txt
Monday 09:00
Tuesday 09:10
Wednesday 10:11
Thursday 11:30
Friday 08:00
Saturday 07:40
Sunday 10:00
#现在要删除处理星期之外的所有字符
#-d represents delete, [0-9] represents all numbers, [:] Represents a colon and a space
$ Cat Test.txt | Tr-d "[0-9][:]"
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
5. Replace with-c for complement set
#有时候在文本中我们只知道要保留的一些字符, a variety of other characters can be used to replace the complement set
$ cat Test.txt
Monday 09:00
Tuesday 09:10
Wednesday 10:11
Thursday 11:30
Friday 08:00
Saturday 07:40
Sunday 10:00
#我们只需要星期, the idea is to replace all but the letters.
#这里,-C: Replaces all characters except the letter with a newline character;-S: Remove extra line breaks
Cat Test.txt|tr-cs "[a-z][a-z]" "\ n"
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
This article from "ZYZDBK" blog, declined reprint!
The TR of the Linux command