linux shell,tr命令

1、说明

tr - translate or delete characters

tr [OPTION]... SET1 [SET2]

Translate, squeeze, and/or delete characters from standard input, writing to standard output.SETs are specified as strings of characters.

tr 用来从标准输入中通过替换或删除操作进行字符转换。使用tr时要提供两个字符串:SET1用于查询,SET2用于处理转换。tr执行时,字符串1中的字符被映射到字符串2中的字符,然后执行转换操作。

2、option

-c 要求字符集为ASCII。用SET2替换SET1中字符集的补集,也就是用set2中字符替换不在set1中的字符

-d 删除SET1中所有输入字符。

-s 删除所有重复出现字符序列,只保留第一个

Translation occurs if -d is not given and both SET1 and SET2 appear.

3、字符范围

[a-z]:[A-Z]:[0-9]:数字串

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

[CHAR*REPEAT] REPEAT copies of CHAR, REPEAT octal if starting with 0

4、示例

1)去除重复的字符

tr -s "[a-z]" < example.txt

cat example.txt | tr -s "[a-z]"

2)删除空行

cat example.txt | tr -s "[\n]"

3)小写到大写

cat example.txt | tr "[a-z]" "[A-Z]"

cat example.txt | tr "[:lower:]" "[:upper:]"

4)替换

cat /etc/passwd | tr -s "[:]" "[\t]"

5)tr -s "[\n]" <test>test11 //输入文件是test,输出文件是test1

6)cat test.txt | tr -d "[0-9][: ]" //删除数字字符和冒号

7)cat test.txt | tr -cs  "[a-z][A-Z]" "\n"  //-c:用换行符替换掉除了字母外的所有字符;-s:删除多余的换行符

5、通过tr实现的功能,都可以通过sed实现。大小写字母的转换,删除不需要的字符比较常用

参考

1http://blog.chinaunix.net/space.php?uid=1813014&do=blog&cuid=364891

2http://unix-cd.com/vc/www/39/2007-11/9971.html

3http://bbs.chinaunix.net/thread-2106256-1-1.html

http://blog.chinaunix.net/space.php?uid=1813014&do=blog&cuid=364891

4http://www.2cto.com/os/201109/104590.html

原文地址:https://www.cnblogs.com/mydomain/p/2192263.html