欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2024-02-23 23:30:34
...

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

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

[email protected]:/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
相关标签: linux tr