linux 中 tr命令

发布时间 2023-06-22 22:43:30作者: 小鲨鱼2018

 

001、-s 将多个连续的字符压缩为一个字符

[root@PC1 test01]# ls
a.txt
[root@PC1 test01]# cat a.txt                   ## 测试数据
ddddfffabccccc
lerrrrdddd
[root@PC1 test01]# cat a.txt | tr -s "a-z"     ## a-z均压缩为一个字母
dfabc
lerd
[root@PC1 test01]# cat a.txt | tr -s "d"       ## 仅压缩d
dfffabccccc
lerrrrd

 

002、删除空行

[root@PC1 test01]# ls
a.txt
[root@PC1 test01]# cat a.txt                  ## 测试数据
ddddfffabccccc


lerrrrdddd
[root@PC1 test01]# cat a.txt | tr -s "\n"     ## 删除空行
ddddfffabccccc
lerrrrdddd
[root@PC1 test01]# cat a.txt
ddddfffabccccc


lerrrrdddd
[root@PC1 test01]# cat a.txt | tr -s "\012"    ## 删除空行
ddddfffabccccc
lerrrrdddd

 

003、将数据转换为一行 

[root@PC1 test01]# ls
a.txt
[root@PC1 test01]# cat a.txt   ## 测试数据
ddddfffabccccc
lerrrrdddd
[root@PC1 test01]# cat a.txt | tr "\n" " " | xargs echo    ## 转换为一行
ddddfffabccccc lerrrrdddd

 

004、删除指定的字符

[root@PC1 test01]# ls
a.txt
[root@PC1 test01]# cat a.txt                       ## 测试数据
ddddfffabccccc
lerrrrdddd
[root@PC1 test01]# cat a.txt | tr -d "df"          ## 删除字符d和f
abccccc
lerrrr

 

005、小写转换为大写

[root@PC1 test01]# ls
a.txt
[root@PC1 test01]# cat a.txt                     ## 测试数据
ddddfffabccccc
lerrrrdddd
[root@PC1 test01]# cat a.txt | tr "a-z" "A-Z"    ## 小写转换为大写
DDDDFFFABCCCCC
LERRRRDDDD

 

006、大写转换为小写

[root@PC1 test01]# ls
a.txt
[root@PC1 test01]# cat a.txt
DDDDFFFABCCCCC
LERRRRDDDD
[root@PC1 test01]# cat a.txt | tr "A-Z" "a-z"        ## 大写转换为小写
ddddfffabccccc
lerrrrdddd

 

007、大小写相互转换

[root@PC1 test01]# ls
a.txt
[root@PC1 test01]# cat a.txt
abEDJ
HKyesLK
[root@PC1 test01]# cat a.txt | tr "a-zA-Z" "A-Za-z"    ## 大小写相互转换
ABedj
hkYESlk

 

008、将多个字符转换为同一个字符

[root@PC1 test01]# ls
a.txt
[root@PC1 test01]# cat a.txt
abEDJ
HKyesLK
[root@PC1 test01]# cat a.txt | tr "abs" "Q"    ## 将多个字符转换为Q
QQEDJ
HKyeQLK