【Linux学习笔记】tr命令

转自: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]"


(如有不足或者侵权的地方,请尽快联系我,我会及时修改或删除,非常感谢)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值