Rootop 服务器运维与web架构

tr (Text Replacer) 文本替换举例

tr用来从标准输入中通过替换或删除操作进行字符转换。tr主要用于删除文件中控制字符或进行字符转换。使用tr时要转换两个字符串:字符串1用于查询,字符串2用于处理各种转换。tr刚执行时,字符串1中的字符被映射到字符串2中的字符,然后转换操作开始。
带有最常用选项的tr命令格式为:
tr -c -d -s [“string1_to_translate_from”] [“string2_to_translate_to”] < input-file
这里:
-c 用字符串1中字符集的补集替换此字符集,要求字符集为ASCII。
-d 删除字符串1中所有输入字符。
-s 删除所有重复出现字符序列,只保留第一个;即将重复出现字符串压缩为一个字符串。
input-file是转换文件名。虽然可以使用其他格式输入,但这种格式最常用。

字符范围
指定字符串1或字符串2的内容时,只能使用单字符或字符串范围或列表。
[a-z]    a-z内的字符组成的字符串。
[A-Z]  A-Z内的字符组成的字符串。
[0-9]   数字串。
\octal  一个三位的八进制数,对应有效的ASCII字符。
[O*n] 表示字符O重复出现指定次数n。因此[O*2]匹配OO的字符串。
tr中特定控制字符的不同表达方式
速记符含义八进制方式
\a Ctrl-G  铃声\007
\b Ctrl-H  退格符\010
\f Ctrl-L  走行换页\014
\n Ctrl-J  新行\012
\r Ctrl-M  回车\015
\t Ctrl-I  tab键\011
\v Ctrl-X  \030

测试文件内容为:
[root@localhost www]# cat txt
123
abc
a
b
c
abcde

1、现将字符a、b、c替换为x、y、z:
[root@localhost www]# cat txt | tr “abc” “xyz” > txt10
[root@localhost www]# cat txt10
123
xyz
x
y
z
xyzde
注意是替换的单个字符,而不是字符串abc

2、统一转换为大写:
[root@localhost www]# cat txt | tr [a-z] [A-Z] > txt11
[root@localhost www]# cat txt11
123
ABC
A
B
C
ABCDE

3、统一转换为小写:
[root@localhost www]# cat txt11
123
ABC
A
B
C
ABCDE
[root@localhost www]# cat txt11 | tr [A-Z] [a-z] > txt12
[root@localhost www]# cat txt12
123
abc
a
b
c
abcde

4、0-9替换为a-j(2种方法):
[root@localhost www]# cat 09.txt
0 1 2 3 4 5 6 7 8 9
[root@localhost www]# cat 09.txt | tr “0-9” “a-j” > aj.txt
[root@localhost www]# cat aj.txt
a b c d e f g h i j
[root@localhost www]# cat 09.txt | tr [0-9] [a-j] > aj2.txt
[root@localhost www]# cat aj2.txt
a b c d e f g h i j

5、删除a、b、c 3个字符:
root@localhost www]# cat txt | tr -d “abc” > txt5.txt
[root@localhost www]# cat txt5.txt
123

de

6、删除换行、制表符:
在第5步时删除abc,导致出现空行,这次删除换行符和制表符,合并为一行。
[root@localhost www]# cat txt5.txt | tr -d “\n\t” > txt6.txt
[root@localhost www]# cat txt6.txt
123de

7、删除连续的字符,只保留第一个字符:
[root@localhost www]# cat aaa.txt
aaabbbcccdef
AAABBBCCCDEF
[root@localhost www]#  cat aaa.txt | tr -s [a-z][A-Z] > aaa2.txt
[root@localhost www]# cat aaa2.txt
abcdef
ABCDEF

8、删除空行:
[root@localhost www]# cat txt5.txt
123

de
[root@localhost www]# cat txt5.txt | tr -s “\n” > txt15.txt
[root@localhost www]# cat txt15.txt
123
de

9、用空格\040替代制表符\011:
[root@localhost www]# cat s.txt
hello    master  #这里空开的部分为tab键敲击出来
hello
[root@localhost www]# cat s.txt | tr -s “\011” “\040” > s2.txt
[root@localhost www]# cat s2.txt
hello master  #替换为空格
hello

原创文章,转载请注明。本文链接地址: https://www.rootop.org/pages/3417.html

作者:Venus

服务器运维与性能优化

评论已关闭。