脚本开发之Shell

shell命令tr

2018-10-19  本文已影响7人  Chaweys
1、
语法:
tr [-c/-d/-s/-t] [str1] [str2]
-c 【(对源字符)符合 str1 的部份不做处理,不符合的剩余部份才进行处理;str2是目标字符集即指定要转换成的目标字符】
-d 【删除指定的字符】
-s 【对连续重复的字符去重成一个字符】
-t 【删除第一字符集较第二字符集多出的字符】
举例:
@1、
echo "HELLO WORD" | tr 'A-Z' 'a-z'
hello word 【对大写字母替换成小写字母】

@2、
echo "hello 123 word 456" | tr -d '0-9'
hello word 【删除数字】

@3、
echo "hello    word" | tr '\t' ' '
hello word 【将制表符\t即tab,替换成空格】

@4、
echo "aa.a,a1 b#$bb 2 c*/cc 3 ddd 4" | tr -d -c '0-9 \n'
1  2  3  4 【删除除了数字和空格外的其它字符,加\n是为了输出后自动换行】
echo "hheelloo" tr -d -c 'e\n' 
ee         【删除除了e之外的其它字符,加\n是为了输出后自动换行】

@5、
cat file | tr -d '[ \t]' 【同时删除空格和制表符】
cat file | tr -d '[abc]' 【同时删除a,b,c三个字符】
cat file | tr -c -s "[a-z]A-Z]" "\n" 【-c,对file里的所有不是字母的,都用\n换行符替换;-s然后又对重复的换行符进行了去重】

@6、
删除换行符\n
file 内容:
I love linux

hello word

cat file | tr -s  "[\n]"
I love linux
hello word   【-s对换行符去重,但是不会将原来字符变成一行,因为是去重所以还保留有一行】

cat file | tr -d  "[\n]"
I love linuxhello word[root@hdc_1 software]#   【直接将原字符变成一行,且[root@hdc_1 software]#  在一行】

@7、
cat file | tr -cs  "[a-z][A-Z]" "\n" 【-c:用换行符替换掉除了字母外的所有字符;-s:删除多余的换行符】
上一篇 下一篇

猜你喜欢

热点阅读