grep 、sed、awk被稱為linux中的"三劍客"。
grep 更适合單純的查找或比對文本
sed 更适合編輯比對到的文本
awk 更适合格式化文本,對文本進行較複雜格式處理
重要:awk 、sed 、grep查找檔案中包含字元的行
awk '{if($0~"listAuths") print}' xxx.log 抽出包含listAuths的行内容
sed -n -e '/listAuths/p' test3.txt 抽出包含listAuths的行内容
grep -n 'listAuths' test3.txt 抽出包含listAuths的行内容
find /root/ -name "te*txt" | xargs grep -in "listAuths" 尋找包含listAuths字元串檔案名:te開頭txt結尾的檔案
awk其實是一門程式設計語言,它支援條件判斷、數組、循環等功能。是以,我們也可以把awk了解成一個腳本語言解釋器。
awk做列印file内容
//列印文本中内容
[[email protected] ~]# echo ddd > testawk
[[email protected] ~]# awk '{print}' testawk
ddd
awk列印列、多列
awk '{print $X}' file 要列印每行的第X列
//列印第二列
[[email protected] ~]# echo 1111 222 > testawk2
[[email protected] ~]# awk '{print $2}' testawk2
222
列印第一列和第二列
[[email protected] ~]# awk '{print $1,$2}' testawk2
1111 222
篩選展現列or加上自己描述一起展現

awk做運算
兩個列做個減法就好

awk -F
awk -F ':',以冒号為分隔符,把輸出的行分隔,預設是空行

awk -F":" '{print $1}' /etc/passwd
awk -F":" '{print $1 $3}' /etc/passwd //$1與$3相連輸出,不分隔
awk -F":" '{print $1,$3}' /etc/passwd //多了一個逗号,$1與$3使用空格分隔
awk -F":" '{print $1 " " $3}' /etc/passwd //$1與$3之間手動添加空格分隔
awk -F":" '{print "Username:" $1 "\t\t Uid:" $3 }' /etc/passwd //自定義輸出
awk -F: '{print NF}' /etc/passwd //顯示每行有多少字段
awk -F: '{print $NF}' /etc/passwd //将每行第NF個字段的值列印出來
awk -F: 'NF==4 {print }' /etc/passwd //顯示隻有4個字段的行
awk -F: 'NF>2{print $0}' /etc/passwd //顯示每行字段數量大于2的行
awk '{print NR,$0}' /etc/passwd //輸出每行的行号
awk -F: '{print NR,NF,$NF,"\t",$0}' /etc/passwd //依次列印行号,字段數,最後字段值,制表符,每行内容
awk -F: 'NR==5{print}' /etc/passwd //顯示第5行
awk -F: 'NR==5 || NR==6{print}' /etc/passwd //顯示第5行和第6行
route -n|awk 'NR!=1{print}' //不顯示第一行
awk -F'' OFS=',' 輸出的格式以X做分隔
[[email protected] ~]# awk '{print}' testawk2
1111 222
[[email protected] ~]# awk '{print $1,$2 "\n33333,444444"}' OFS=',' testawk2 > testawk3
[[email protected] ~]# cat testawk3
1111,222
33333,444444
sed 的使用
列印具體行數内容
[[email protected] ~]# cat testawk3
1111,222
33333,44444
111124,33333,qrrr
123we,ert4,123
1112222
[[email protected] ~]# sed -n '2p' testawk3
33333,44444
[[email protected] ~]# sed -n '2,4p' testawk3
33333,44444
111124,33333,qrrr
123we,ert4,123
顯示包含"1111"的行到包含"qrrr"的行之間的行
sed -n '/1111/,/qrrr/p' testawk3

列印1-4行,并顯示行号
sed -n -e '1,4p' testawk3

sed 替換部分字段輸出
sed 's/aa/AA/' test3.txt
grep
1基礎正規表達式
grep 工具,以前介紹過。
grep -[acinv] '搜尋内容串' filename
-a 以文本檔案方式搜尋
-c 計算找到的符合行的次數
-i 忽略大小寫
-n 順便輸出行号
-v 反向選擇,即找 沒有搜尋字元串的行
其中搜尋串可以是正規表達式! grep -n '[0-9]' xxx.txt
2 利 用[]搜尋集合字元
[] 表示其中的某一個字元 ,例如[ade] 表示a或d或e
[email protected]:~/tmp$ grep -n 't[ae]st' regular_express.txt
8:I can't finish the test.
9:Oh! the soup taste good
收搜包含xxx的檔案,并且檔案中包含aa字元串
find /root/ -name "te*txt" | xargs grep -in "aa"