将字符进行替换压缩和删除,tr命令 可以对来自标准输入的字符进行替换、压缩和删除。它可以将一组字符变成另一组字符,经常用来编写优美的单行命令,作用很强大。
tr [选项] [字符串1] [字符串2]
> echo "HELLO WORLD" | tr 'A-Z' 'a-z'
hello world
'A-Z' 和 'a-z'都是集合,集合是可以自己制定的,例如:'ABD-}'、'bB.,'、'a-de-h'、'a-c0-9'都属于集合,集合里可以使用'\n'、'\t',可以可以使用其他ASCII字符。
> echo "hello 123 world 456" | tr -d '0-9'
hello world
> cat text | tr '\t' ''
> echo aa.,a 1 b#$bb 2 c*/cc 3 ddd 4 | tr -d -c '0-9 \n'
1 2 3 4
此例中,补集中包含了数字0~9、空格和换行符\n,所以没有被删除,其他字符全部被删除了。
> echo "thissss is a text linnnnnnne." | tr -s ' sn'
this is a text line.
> cat a.log | tr "\r" "\n" > b.log
//或者
> cat a.log | tr -d "\r" > b.log
> echo -e "1\n\n\n2\n\n\n3\n\n\n" | tr -s '\n'
1
2
3
> echo -e "1\n\n\n2\n\n\n3\n\n\n" | tr -d '\n'
123
-
> echo "2021 03 01" |tr -s ' ' '-'
2021-03-01
> echo "2021assefdf03fff01" |tr -d -c '[0-9]'
20210301
原文链接:https://rumenz.com/rumenbiji/linux-tr.html
微信公众号:入门小站
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有