字符转换命令tr

tr 用来从标准输入中通过替换或删除操作进行字符转换.tr主要用于删除文件中控制字符或进行字符在转换.使用tr时要转换两个字符串:字符串1用于查询,字符串2用于处理各种转换.tr刚执行时,字符串1中字符被映射到字符串2中的字符,然后转换操作开始.

语法:

tr  [-cdst] [SET1] [SET2] [>newfile] [<file]

参数:

-c : complement 用SET2替换SET1中没有包含的字符;

-d : delete 删除信息当中的SET1这个字符串;

-s : 替换掉重复的字符,只保留第一个,即将重复出现的字符串压缩为一个字符串;

-t : truncate-set1,将SET1用SET2转换,一般缺省值为-t;

SET1/2 : 字符集;

>newfile :我们可以将结果导入新的文件保存;

<file : 我们可以通过<来读入file;

字符范围:

[a-z]/[A-Z] : a-z/A-Z内的字符组成的字符串;

[0-9] : 数字串;

\octal : 一个三位数的八进制数,对应有效的ASCII字符;

[0*n] : 表示字符0重复出现指定次数n,如[0*2]匹配00的字符串;

 

范例1:  将/etc/passwd 中的小写字符变成大写字符

# cat /etc/passwd | tr [a-z] [A-Z]

同样我们可以通过<读入/etc/passwd,如下

#tr [a-z] [A-Z] < /etc/passwd

 

范例2: 将/etc/passwd 转存成dos断行到/root/passwd中,再将^M符号删除

# cp /etc/passwd /root/passwd && unix2dos /root/passwd

cp: overwrite `/root/passwd’? y

unix2dos: converting file /root/passwd to DOS format …

# file /etc/passwd /root/passwd

/etc/passwd:  ASCII text

/root/passwd: ASCII text, with CRLF line terminators

这里牵扯到unix2dos 命令,可以通过yum -y install unix2dos直接安装.

# cat /root/passwd | tr -d ‘\r’ > /root/passwd.linux

这里的”\r”指的是dos的断行字符

# ll /etc/passwd /root/passwd*

-rw-r–r–. 1 root root 891 Apr  2 06:01 /etc/passwd

-rw-r–r–. 1 root root 911 Apr 17 10:46 /root/passwd

-rw-r–r–. 1 root root 891 Apr 17 10:47 /root/passwd.linux

处理过后,发现文件大小与原来的/etc/passwd就一致了.

 

范例3: 删除空白行

删除空白行就是删除换行符/n

注意:这些空白行上只有回车符,没有空格符

# cat test.txt

I lovve linux!

 

Hello World!

 

Shell is worthy to been studied!

这里使用换行符的转义字符\n

注意:若用-d,则会删除所有的换行符,如下:

# cat test.txt | tr -d [“\n”]

I lovve linux!Hello World!Shell is worthy to been studied!

而此处用-s删除多余的换行符呢,如下:

[root@sqj2015 ~]# cat test.txt | tr -s [“\n”]

I lovve linux!

Hello World!

Shell is worthy to been studied!

 

范例4:删除指定的字符

# cat test.txt

Monday 1:00

Tuessday 2:00

Wednesday 3:00

现在要删除处理星期之外的所有字符

-d代表删除,[0-9]代表所有的数字,[: ]代表冒号和空格

# cat test.txt | tr -d “[0-9][: ]”

Monday

Tuessday

Wednesday

 

范例5: 利用-c进行补集的替换

有时候在文本中我们只知道要保留一些字符,其他字符种类繁多,就可以使用补集的替换

# cat test.txt

Monday 1:00

Tuessday 2:00

Wednesday 3:00

我们只需要星期,则思路就是除了字母,其他统统替换掉

这里,-c用换行符替换掉除了字符外的所有字符,-s删除多余的换行符

# cat test.txt | tr -cs “[a-z][A-Z]” “\n”

Monday

Tuessday

Wednesday