Use of Linux tr Command

  • 2021-08-28 21:38:40
  • OfStack

1. Introduction

tr is used to convert or delete a paragraph of text. tr is translate (abbreviation of transformation), and the English schematic of function is translate or delete characters. All the functions of tr can be completed by sed, and tr can be regarded as a minimal implementation of sed1.

2. Format


tr [OPTION]... SET1 [SET2]

3. Options


-c,-C,--complement : Set the character set <character set1> Delete or convert characters other than the character set <character set2> The last of the 1 Characters (if you specify more than one character). See example 6 . 
-d,--delete Delete the SET1 This string. 
-s,--squeeze-repeats Compress duplicate characters, leaving only 1 A. 
--help Displays help information. 
--version Displays version information. 

4. Examples

(1) Change all lowercase characters in the information output by last to uppercase characters.


last|tr '[a-z]' '[A-Z]'
// Or 
last|tr [a-z] [A-Z]

(2) Remove the colon: from the message outputted/etc/passwd.


cat /etc/passwd | tr -d ':'

(3) Transform dos file into unix file.


cat /etc/passwd | tr -d '\r'

(4) Delete blank lines


cat file | tr -s "\n" > new_file

(5) Replace "abc" in the file file with "xyz".


cat file | tr "abc" "xyz" > new_file

Note: All the letters "a" appearing in file here are replaced with "x", "b" with "y", "c" with "z", instead of replacing the string "abc" with the string "xyz".

(6) Delete and replace characters outside the specified character set.


// Replaces characters outside the specified character set 
[b3335@MIC ~]$ echo alv blv|tr -c 'lv ' "x"
xlv xlvx

// Deletes characters outside the specified character set 
[b3335@MIC ~]$ echo alv blv|tr -cd 'lv'
lvlv

The above is the use of Linux tr command details, more information about Linux tr command please pay attention to other related articles on this site!


Related articles: