TR cmd/shell

来源:互联网 发布:ios编程用什么语言 编辑:程序博客网 时间:2024/04/29 17:14

TR

tr是linux命令常用命令,其全称“Text Replacer”,该命令用于进行文本替换。
tr用来从标准输入中通过替换或删除操作进行字符转换。 tr主要用于删除文件中控制字符或进行字符转换。
特别要注意一点:tr 只能进行字符的替换、缩减和删除,不能用来替换字符串。
最常用选项的tr命令格式为:
tr -c -d -s ["string1_to_translate_from"] ["string2_to_translate_to"] file
这里:
-c 用字符串1中字符集的补集替换此字符集,要求字符集为ASCII。
-d 删除字符串1中所有输入字符。
-s 删除所有重复出现字符序列,只保留第一个;即将重复出现字符串压缩为一个字符串。
file是转换文件名。虽然可以使用其他格式输入,但这种格式最常用。
字符范围
指定字符串1或字符串2的内容时,只能使用单字符或字符串范围或列表。
[a-z] a-z内的字符组成的字符串。
[A-Z] A-Z内的字符组成的字符串。
[0-9] 数字串。
\octal 一个三位的八进制数,对应有效的ASCII字符。
[O*n] 表示字符O重复出现指定次数n。因此[O*2]匹配OO的字符串。
tr中特定控制字符的不同表达方式
速记符含义八进制方式
\a Ctrl-G  铃声\007
\b Ctrl-H  退格符\010
\f Ctrl-L  走行换页\014
\n Ctrl-J  新行\012
\r Ctrl-M  回车\015
\t Ctrl-I  tab键\011
\v Ctrl-X  \030

应用例子

(1)去除oops.txt里面的重复的小写字符 ( #  -s会保留第一个字符)

[root@localhost ~]# cat oops.txt
ddddfffabccccc
lerrrrdddd
[root@localhost ~]# tr -s "[a-z]" < oops.txt > result.txt
[root@localhost ~]# cat result.txt
dfabc
lerd

(2)删除空行

[root@localhost ~]# cat oops.txt
ddddfffabccccc
lerrrrdddd
[root@localhost ~]#  tr -s "[\012]" < oops.txt > result.txt
[root@localhost ~]# cat result.txt
ddddfffabccccc
lerrrrdddd

(3)删除所有空行

[root@localhost ~]# cat oops.txt
ddddfffabccccc
lerrrrdddd
[root@localhost ~]# tr -d "[\012]" < oops.txt > result.txt
[root@localhost ~]# cat result.txt
ddddfffabccccclerrrrdddd

(4)小写到大写

[root@localhost ~]# cat oops.txt
ddddfffabccccc
errrrdddd
[root@localhost ~]# cat oops.txt | tr "[a-z]" "[A-Z]" > result.txt
[root@localhost ~]# cat result.txt
DDDDFFFABCCCCC
ERRRRDDDD

(5)删除指定的字符(# -d 与 -s 不同,-d会全部删除,但-s会保留第一个)

[root@localhost ~]# cat oops.txt
ddddfffabccccc
errrrdddd
[root@localhost ~]# cat oops.txt | tr -d "[bd]" > result.txt
[root@localhost ~]# cat result.txt
fffaccccc
errrr
[root@localhost ~]# cat oops.txt | tr -s "[bd]" > result.txt
[root@localhost ~]# cat result.txt
dfffabccccc
errrrd

(6)替代指定的字符(#一对一的替代)

[root@localhost ~]# cat oops.txt
ddddfffabccccc
errrrdddd
[root@localhost ~]# cat oops.txt | tr "[bd]" "[BD]" > result.txt
[root@localhost ~]# cat result.txt
DDDDfffaBccccc
errrrDDDD
原创粉丝点击