版权声明:本文为博主chszs的原创文章,未经博主允许不得转载。 https://blog.csdn.net/chszs/article/details/4076089
UNIX Shell 编程(5)
过滤器tr用来转换来自标准输入的字符。格式:
tr from-chars to-chars
from-chars 和 to-chars 是一个或多个字符。例如:
[root@localhost programs]# cat intro
The Unix operating system was pioneered by Ken
Thompson and Dennis Ritchie at Bell Laboratories
in the late 1960s. One of the primary goals in
the design of the Unix system was to create an
environment that promoted efficient program
developments.
[root@localhost programs]# tr e x < intro
Thx Unix opxrating systxm was pionxxrxd by Kxn
Thompson and Dxnnis Ritchix at Bxll Laboratorixs
in thx latx 1960s. Onx of thx primary goals in
thx dxsign of thx Unix systxm was to crxatx an
xnvironmxnt that promotxd xfficixnt program
dxvxlopmxnts.
-s选项
用于压缩to-chars中重复的字符。例如:
[root@localhost programs]# cat lotsapaces
This is an example of a
file that contains a lot
of blank spaces
[root@localhost programs]# tr -s ' ' < lotsapaces
This is an example of a
file that contains a lot
of blank spaces
-d选项
用于删除输入流中的字符,格式为:
tr -d from-chars
删除所有空格
[root@localhost programs]# tr -d ' ' < lotsapaces
Thisisanexampleofa
filethatcontainsalot
ofblankspaces
用sed命令也可实现:
[root@localhost programs]# sed 's/ //g' lotsapaces
tr命令综合实例:
————————————————————————————————————
tr 'X' 'x' 把所有大些X转换为小写x
tr '()' '{}' 把所有小括号换为大括号
tr '[A-Z]' '[N-ZA-M]' 把A-M字母转换为N-Z,把N-Z转换为A-M
tr -d '/14' 删除所有换页字符
tr -d '[0-9]' 删除所有数字
grep命令可以从一个或多个文件中搜索特定的字符串模式,格式为:
grep pattern files
例如,从文件intro找出含Unix的行:
[root@localhost programs]# grep Unix intro
-v选项 显示不包含的行
例如,显示intro文件中所有不包括Unix的行:
[root@localhost programs]# grep -v 'Unix' intro
例如,显示当前目录下所有文件中包含Unix或unix的行:
[root@localhost programs]# grep '[Uu]nix' *
intro:The Unix operating system was pioneered by Ken
intro:the design of the Unix system was to create an
-l选项 只给出包含给定模式的文件列表,而不给出文件中的匹配行。
[root@localhost programs]# grep -l '[Uu]nix' *
intro
-n选项 文件中符合指定模式的每一行前都加上该行在文件中的相对行号。
[root@localhost programs]# grep -n 'Unix' *
intro:1:The Unix operating system was pioneered by Ken
intro:4:the design of the Unix system was to create an
sort命令:
[root@localhost programs]# cat names
Tony
Emanuel
Lucy
Ralph
Fred
[root@localhost programs]# sort names
-u选项 在输出结果中去除重复的行
-r选项 颠倒排序顺序
[root@localhost programs]# sort -r names
sort的输出重定向:可用-o选项,也可用>符号
[root@localhost programs]# sort -r names > sorted_name1
[root@localhost programs]# sort names -o sorted_name2
-n选项 按第一列进行排序
如:
[root@localhost programs]# cat data2
5 27
2 12
3 33
23 2
-5 11
15 6
14 -9
[root@localhost programs]# sort -n data2
[root@localhost programs]# uniq names
[root@localhost programs]# sort names | uniq