转自:https://www.cnblogs.com/hello-wei/p/10365215.html
-
功能
tr命令:用于转换和删除字符
-
格式
格式为:“tr [参数] [字符串1原始字符] [目标字符] input_file
-
字符范围
使用tr时,可以指定字符串列表或范围作为形成字符串的模式。这看起来很像正则表达式,但实际上不是。指定字符串1或字符串2的内容时,只能使用单字符或字符串范围或列表。
大部分tr变种支持字符类和速记控制字符。
字符类格式为[:class],包含数字、希腊字母、空行、小写、大写、ctrl键、空格、点记符、图形等等
-
示例
1、去除重复出现的字符 -s 因为都是字母,故使用[a-z]
[python@master2 tr]$ more a.txt
helloo worldddd
[python@master2 tr]$ cat a.txt |tr -s "[a-z]"
helo world
[python@master2 tr]$ tr -s "[a-z]" < a.txt
helo world
2、要删除空行,可将之剔出文件。使用-s来做这项工作。换行的八进制表示为\012
[python@master2 tr]$ more b.txt
this is a one line
two
thress
foure
[python@master2 tr]$
[python@master2 tr]$
[python@master2 tr]$ tr -s "[\012]"< b.txt
this is a one line
two
thress
foure
[python@master2 tr]$ tr -s "[\n]" < b.txt
this is a one line
two
thress
foure
3、删除指定字符 #-d代表删除,[0-9]代表所有的数字,[: ]代表冒号和空格
[python@master2 tr]$ more c.txt
Monday 09:00
Tuesday 09:10
Wednesday 10:11
Thursday 11:30
Friday 08:00
Saturday 07:40
Sunday 10:00
[python@master2 tr]$ cat c.txt |tr -d "[0-9][:]"
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
4、想把某个文档进行大小写替换,先使用cat命令读取待处理的文本,然后通过管道符把这些文本内容传递给tr命令进行替换操作:
cat anaconda-ks.cfg | tr "[a-z]" "[A-Z]"
(如有不足或者侵权的地方,请尽快联系我,我会及时修改或删除,非常感谢)