Tr is used to delete control characters in a file or convert characters.
Syntax: tr [-c/d/s/t] [SET1] [SET2]
SET1: Character Set 1
SET2: Character Set 2
-C: complement. Use SET2 to replace characters not included in SET1.
-D: delete all characters in SET1, without conversion
-S: squeeze-repeats, compresses repeated characters in SET1
-T: truncate-set1, which converts SET1 to SET2. The default value is-t.
1. Remove repeated characters
# Compressing several consecutive identical characters into one character
$ Echo aaacccddd | tr-s [a-z]
Acd
$ Echo aaacccddd | tr-s [abc]
Acddd
2. Delete blank rows
# Deleting blank rows is to delete linefeeds/n
# Note: There are only carriage return characters and no space characters on these blank lines.
$ Cat test.txt
I love linux!
Hello World!
Shell is worthy to been studied
# Use the Escape Character \ n of the line break here
# Note: extra line breaks are deleted with-s. If-d is used, all line breaks are deleted.
$ Cat test.txt | tr-s ["\ n"]
I love linux!
Hello World!
Shell is worthy to been studied
# You can also use the octal character \ 012, \ 012, and \ n as line breaks.
$ Cat test.txt | tr-s "[\ 012]"
I love linux!
Hello World!
Shell is worthy to been studied
3. case-insensitive Conversion
# Convert 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
# Convert 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
# Conversion using character classes
# [: Lower:] indicates lower-case letters, and [: upper:] indicates upper-case letters.
$ Echo "Hello World I Love You" | tr [: lower:] [: upper:]
HELLO WORLD I LOVE YOU
4. Delete the specified character
$ Cat test.txt
Monday
Tuesday
Wednesday 10: 11
Thursday 11: 30
Friday
Saturday
Sunday
# Delete All characters outside the processing week
#-D Indicates deletion, [0-9] indicates all numbers, and [:] indicates colons and spaces.
$ Cat test.txt | tr-d "[0-9] [:]"
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
5. Use-c to replace the complementary set
# Sometimes we only know the characters to be retained in the text. If there are many other types of characters, we can replace them with supplements.
$ Cat test.txt
Monday
Tuesday
Wednesday 10: 11
Thursday 11: 30
Friday
Saturday
Sunday
# If we only need a week, the idea is to replace all the letters except letters.
# Here,-c: replace all characters except letters with line breaks;-s: Delete unnecessary line breaks
Cat test.txt | tr-cs "[a-z] [A-Z]" \ n"
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
Conclusion: the conversion of uppercase and lowercase letters is commonly used to delete unnecessary characters. Tr syntax is simple and easy to use.
Author: "To_Be_Monster_Of_IT"