版權聲明:本文為部落客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