码迷,mamicode.com
首页 > 其他好文 > 详细

shell学习之tr命令

时间:2014-07-15 11:20:57      阅读:232      评论:0      收藏:0      [点我收藏+]

标签:shell   tr命令   

tr命令不接受指定的文件参数,而只是对标准输入进行翻译, trtranslate的简写,亦即翻译,需要注意的是,它不能翻译句子,只能翻译单个字符。

首先,定义变量:

    [root@tong]#A=1,,2,,,3,,,4,,,5

下面以示例对该命令以及其常用选项进行介绍。

示例:

1.  无选项设置情况

    [root@tong]# echo $A | tr  ‘,‘ ‘ ‘    
    1 2   3   4   5
    [root@tong]# echo $A | tr [2-4] [b-d]
    1,,b,,,c,,,d,,,5
    [root@tong]# echo $A | tr "23""bc"
    1,,b,,,c,,,4,,,5

注意,这里不是对字符串的替换,而是将“2”替换为“b”,“3”替换为“c”。

常用:小写 --> 大写

    # tr [a-z] [A-Z]

2.  选项“-s”,删除所有重复出现字符序列,只保留第一个,即将重复出现字符串压缩为一个字符串。

    [root@tong]#echo $A | tr -s ‘,‘    
    1,2,3,4,5
    [root@tong]#echo $A | tr -s ‘,‘ ‘ ‘
    12 3 4 5

3.  选项“-d”,删除字符串指定的所有输入字符。

    [root@tong]#echo $A | tr -d "23"    
    1,,,,,,,,4,,,5
    [root@tong]#echo $A | tr -d  ‘,‘
    12345

常用:删除Windows文件中的‘^M‘字符

    # tr -d"/r"

4.  选项“-c”,对字符串中字符集的补集做替换,要求字符集为A S C I I

    [root@tong]# echo $A | tr -c  [1-5] ‘%’    
    1%%2%%%3%%%4%%%5


本文出自 “linux” 博客,请务必保留此出处http://4983206.blog.51cto.com/4973206/1438109

shell学习之tr命令,布布扣,bubuko.com

shell学习之tr命令

标签:shell   tr命令   

原文地址:http://4983206.blog.51cto.com/4973206/1438109

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!