Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2231777
  • 博文数量: 533
  • 博客积分: 8689
  • 博客等级: 中将
  • 技术积分: 7046
  • 用 户 组: 普通用户
  • 注册时间: 2010-11-26 10:00
文章分类

全部博文(533)

文章存档

2024年(2)

2023年(4)

2022年(16)

2014年(90)

2013年(76)

2012年(125)

2011年(184)

2010年(37)

分类: LINUX

2011-11-25 18:09:38


linux中tr的使用  

2010-09-22 15:20:50|  分类: Linux|字号 订阅

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


阅读(1161) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~