MSN: Phenzer@hotmail.com 欢迎加为好友讨论测试

tr命令实例讲解

上一篇 / 下一篇  2010-11-11 10:24:57 / 个人分类:Linux

一、tr格式
tr主要用户删除文件中的控制字符或进行字符转换。
格式:
tr -c -d -s ["string1_to_translate_from"] ["string2_to_translate_to"] file
-c 用字符串1中字符集的补集替换此字符集,要求字符集为ASCII。
-d 删除字符串1中所有输入字符
-s 删除所有重复出现字符序列,只保留一个;即将重复出现的字符串压缩为一个。
二、实例
1.删除重复字符串
[root@RHEL5 shell]# cat oops.txt 
And the cowwwwws went homeeeeee
Or did the yyyy
[root@RHEL5 shell]# tr -s "[a-z]" < oops.txt   
And the cows went home
Or did the y
[root@RHEL5 shell]# cat oops.txt | tr -s "[a-z]"
And the cows went home
Or did the y
2.删除空行
[root@RHEL5 shell]# cat plane.txt
235424  aaaaaaaaaaa



342311  bbbbbbbbbbb

232321  ccccccccccc
464644  ddddddddddd




[root@RHEL5 shell]# tr -s "\012" < plane.txt
235424  aaaaaaaaaaa
342311  bbbbbbbbbbb
232321  ccccccccccc
464644  ddddddddddd
命令中的"012"是换行的八进制形式,也可以用"\n",如下
[root@RHEL5 shell]# tr -s "\n" < plane.txt
235424  aaaaaaaaaaa
342311  bbbbbbbbbbb
232321  ccccccccccc
464644  ddddddddddd
3.大小写转换
[root@RHEL5 shell]# cat myfile.txt 
May Day
May Day
May Day
Going Down
May Day.
[root@RHEL5 shell]# tr "[A-Z]" "[a-z]"<  myfile.txt >low.txt
[root@RHEL5 shell]# cat low.txt 
may day
may day
may day
going down
may day.

4.删除文件file中出现的"Snail"字符
# cat file | tr -d "Snail" > new_file
这里,凡是在file文件中出现的'S','n','a','i','l'字符都会被删除!而不是紧紧删除出现的"Snail”字符串。
5.删除文件file中出现的换行'\n'、制表'\t'字符
# cat file | tr -d "\n\t" > new_file
不可见字符都得用转义字符来表示的。
6.删除空行
# cat file | tr -s "\n" > new_file
7.删除Windows文件“造成”的'^M'字符
# cat file | tr -d "\r" > new_file
或者
# cat file | tr -s "\r" "\n" > new_file

TAG: 命令 实例 tr

 

评分:0

我来说两句

Open Toolbar