Linux--使用tr命令对字符串做处理

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_36485376/article/details/81350153

tr命令可以对来自标准输入的字符进行转换,压缩和删除处理,很强大

tr命令帮助信息的部分内容如下:

root@ubuntu:/home/fl# tr --help
Usage: tr [OPTION]... SET1 [SET2]
Translate, squeeze, and/or delete characters from standard input,
writing to standard output.

  -c, -C, --complement    use the complement of SET1
  -d, --delete            delete characters in SET1, do not translate
  -s, --squeeze-repeats   replace each sequence of a repeated character
                            that is listed in the last specified SET,
                            with a single occurrence of that character
  -t, --truncate-set1     first truncate SET1 to length of SET2
      --help     display this help and exit
      --version  output version information and exit

删除字符

root@ubuntu:/home/fl# echo "Hello 123 word" | tr -d "0-9"
Hello  word

使用补集

如把标准输入里面的大写字母和换行符之外的字符删掉

HWroot@ubuntu:/home/fl# echo "Hello Word!" | tr -d -c "A-Z\n"
HW

字符串替换

root@ubuntu:/home/fl# echo "Hello Word!" | tr "!" "."
Hello Word.

root@ubuntu:/home/fl# echo "Hello Word!" | tr "Word" "A"
HellA AAAA!

大小写转换

root@ubuntu:/home/fl# echo "aaBB" | tr "a-z" "A-Z"
AABB

root@ubuntu:/home/fl# echo "aaBB" | tr "[:lower:]" "[:upper:]"
AABB

字符去重

root@ubuntu:/home/fl# echo "nihaooo" | tr -s "o"
nihao

猜你喜欢

转载自blog.csdn.net/weixin_36485376/article/details/81350153