1. 程式人生 > 其它 >linux系統中tr命令

linux系統中tr命令

1、tr命令 -s 引數將多個連續的字元壓縮為一個字元

[root@centos79 test]# ls
a.txt
[root@centos79 test]# cat a.txt
aaabbbaaaccc
a
a
bbbb
ddddcccc
[root@centos79 test]# tr -s abcd < a.txt    ## 將任一連續的a、b、c、d字元壓縮為一個字元
abac
a
a
b
dc
[root@centos79 test]# ls
a.txt
[root@centos79 test]# cat a.txt
aaabbbaaaccc
bbbb
ddddcccc
[root@centos79 test]# cat a.txt 
| tr -s a Y ## 將多個連續的a壓縮為Y YbbbYccc bbbb ddddcccc [root@centos79 test]# cat a.txt | tr -s ab YM ## 將多個連續的a、連續的b分別壓縮為Y和M YMYccc M ddddcccc

擴充套件:刪除空白行

[root@centos79 test]# ls
a.txt
[root@centos79 test]# cat -A a.txt
$
$
aaabbbaaaccc$
$
$
bbbb$
$
$
ddddcccc$
[root@centos79 test]# cat a.txt | tr -s "
\n"
aaabbbaaaccc bbbb ddddcccc [root@centos79 test]# cat a.txt | tr -s "\n" | sed 1d aaabbbaaaccc bbbb ddddcccc

2、 -d引數刪除指定的字元

[root@centos79 test]# ls
a.txt
[root@centos79 test]# cat a.txt
aaabbbaaaccc
bbbb
ddddcccc
[root@centos79 test]# cat a.txt | tr -d c
aaabbbaaa
bbbb
dddd
[root@centos79 test]# cat a.txt 
| tr -d cb aaaaaa dddd [root@centos79 test]# cat a.txt | tr -d cba dddd

3、-t引數進行字元的替換

[root@centos79 test]# ls
a.txt
[root@centos79 test]# cat a.txt
aaabbbaaaccc
bbbb
ddddcccc
[root@centos79 test]# cat a.txt | tr -t a X
XXXbbbXXXccc
bbbb
ddddcccc
[root@centos79 test]# cat a.txt | tr -t acd XYM   
XXXbbbXXXYYY
bbbb
MMMMYYYY

可以省略-t:

[root@centos79 test]# cat a.txt | tr  a X   
XXXbbbXXXccc
bbbb
ddddcccc
[root@centos79 test]# cat a.txt | tr  acd XYM   ## 連續替換多個字元
XXXbbbXXXYYY
bbbb
MMMMYYYY

擴充套件:大小寫轉換

[root@centos79 test]# cat a.txt
aaaccc
BBB
DDDcccc
[root@centos79 test]# cat a.txt | tr -t a-z A-Z
AAACCC
BBB
DDDCCCC
[root@centos79 test]# cat a.txt
aaaccc
BBB
DDDcccc
[root@centos79 test]# cat a.txt | tr -t A-Z a-z
aaaccc
bbb
dddcccc

4、-c引數 將指定字元外的字元替換為指定字元

[root@centos79 test]# cat a.txt
aaabbbaaaccc
bbbb
ddddcccc
[root@centos79 test]# cat a.txt | tr -c a M   ## 將a字元外的字元全部替換為M
aaaMMMaaaMMMMMMMMMMMMMMMMMM[root@centos79 test]# cat a.txt | tr -c a M | sed 's/$/\n/'
aaaMMMaaaMMMMMMMMMMMMMMMMMM
[root@centos79 test]# cat a.txt | tr -c ab M | sed 's/$/\n/'  ## 將ab外的字元全部替換為M
aaabbbaaaMMMMbbbbMMMMMMMMMM

參考:https://www.cnblogs.com/faberbeta/p/linux-shell003.html