[shell基础]——tr命令
(1) tr 字符替换
测试文本内容 # cat /etc/hosts 127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4 ::1 loalhost localhost.localdomain localhost6 localhost6.localdomain6
把小写字母替换成大写字母 # tr "[a-z]" "[A-Z]" < /etc/hosts 127.0.0.1 LOCALHOST LOCALHOST.LOCALDOMAIN LOCALHOST4 LOCALHOST4.LOCALDOMAIN4 ::1 LOALHOST LOCALHOST.LOCALDOMAIN LOCALHOST6 LOCALHOST6.LOCALDOMAIN6
把:替换成空格 # tr ":" " " < /etc/hosts 127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4 1 loalhost localhost.localdomain localhost6 localhost6.localdomain6
注意这种是3-a、4-b、5-c的一一对应替换方式 # echo 112233445566 | tr "345" "abc" 1122aabbcc66
(2) -s 将连续相同的字符压缩成1个字符
# echo 1122333444555 | tr -s "3" 11223444555 # echo 1122333444555 | tr -s "12345" 12345 去除空行 # cat 1.txt | tr -s "[\n]"
(3) tr -s " " " " 替换且压缩
# cat 5.txt root tty1 2016-05-22 18:11 (:0) 把空格替换成换行符,并且压缩了(因为原本中间是有多个空格的) # tr -s " " "\n" <5.txt root tty1 2016-05-22 18:11 (:0) 对比一下不压缩的情况 # tr " " "\n" <5.txt root tty1 2016-05-22 18:11 (:0)
(4) -d 删除
# cat 1.txt 123And the cowwwwwssssss went homeeeeeeeee 456i havvvvve 789theyyyyyyyyy 删除所有字母 # tr -d "A-z" < 1.txt 123 456 789 tr支持删除 \n\t等字符 # cat 1.txt | tr -d "\n" And the cowwwwwssssss went homeeeeeeeeei havvvvve theyyyyyyyyy[root@sxjy rh7]# 删除“And”字符 # tr -d [And] < 1.txt 123 the cowwwwwssssss wet homeeeeeeeee 456i havvvvve 789theyyyyyyyyy
删除转换控制字符: ^的八进制代码是136,^M是015,tab键是011,^Z是032 # cat 1.txt | tr -d '[\011\015]'