awk 是 Linux 中的文本處理與分析命令,功能簡單卻強悍,同時它也是一門程式語言。它以「行」為單位處理文本,處理日誌檔案時特別高效。
man 文檔摘要:gawk 是 GNU 計畫對 AWK 語言的實作,符合 POSIX 1003.1 標準,並在 System V Release 4 版 awk 的基礎上加入了貝爾實驗室的擴展與若干 GNU 專屬特性。可見 Linux 中的 awk(gawk)確實強大。
方式一:awk [options] 'script' [var=value] file(s)
方式二:awk [options] -f scriptfile [var=value] file(s)
其中 options 為命令選項;方式一的 'script' 是 awk 的處理程式;var=value 是變量;file(s) 為被處理的文本,可一次處理多個檔案。方式二的 -f scriptfile 表示把處理程式放進腳本檔案。
awk 預設分隔符是空格,預設以空格切割行文本。
-F fs --field-separator fs
Use fs for the input field separator (the value of the FS predefined variable).
# 案例 1:預設分隔符為 " "
$ echo "hello hh" | awk '{print $1;print $2}'
hello
hh
# 案例 2:以 ":" 分隔
$ echo "hello:hh" | awk -F : '{print $1;print $2}'
hello
hh
$1、$2 是位置變量,分別代表第一、第二個字段。
n 表示第 n 個字段,也就是切割後第 n 個位置上的字串;$0 表示整行;NF 表示最後一個位置的字串,NF-1 為倒數第二個,依此類推。
$ cat pass.log # 取自 /etc/passwd 的片段
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
$ awk -F : '{print;}' pass.log # print 預設印整行,等同 $0
$ awk -F : '{print $0;}' pass.log # 明確印整行
$ awk -F : '{print $1 " " $NF;}' pass.log
root /bin/bash
bin /sbin/nologin
daemon /sbin/nologin
當處理邏輯複雜時,通常用 -f 把程式指定到腳本檔。
-f program-file --file program-file
Read the AWK program source from the file program-file, instead of from the
first command line argument. Multiple -f options may be used.
$ vi sc.awk
{print $1 " " $NF}
$ awk -F : -f sc.awk pass.log
root /bin/bash
bin /sbin/nologin
daemon /sbin/nologin
此時處理程式不必再放在單引號中。若不熟悉 vi,也可用 echo "{print $1 \" \" $NF}" > sc.awk 產生程式檔。
$ vi sc.awk
# awk program's Begin block ← 註釋
BEGIN{print "here is the awk begin!!"}
{print $1 " " $NF}
$ awk -F : -f sc.awk pass.log
here is the awk begin!! ← BEGIN 最先執行,且只執行一次
root /bin/bash
bin /sbin/nologin
daemon /sbin/nologin
主體部分寫在 BEGIN 之後、END 之前,以 {} 表示,每處理一行就執行一次。
BEGIN{print "here is the awk begin!!"}
{ print "this is main"; print $1 }
END 區塊在最後執行,也只執行一次:
BEGIN{print "here is the awk begin!!"}
{ print $1 }
END{ print "ok,awk operate to the end" }
宣告方式為 varName=varValue,使用時直接寫變量名,不像 bash 需要 $ 起首。
BEGIN{ nu=0; } # 宣告變量表示行號
{ nu++; print nu " " $0 } # 每處理一行,行號 +1
END { print "totall lines is " nu; }
$ awk -F : -f sc.awk pass.log
1 root:x:0:0:root:/root:/bin/bash
2 bin:x:1:1:bin:/bin:/sbin/nologin
3 daemon:x:2:2:daemon:/sbin:/sbin/nologin
totall lines is 3
方式一:awk [options] -v varname=varvalue 'script' file(s)
方式二:awk [options] 'script' varname=varvalue file(s)
$ awk -F : -v aa="haima" '{print aa " " $1}' pass.log
haima root
haima bin
haima daemon
$ awk -F : '{print aa " " $1}' aa="haima" pass.log # 方式二
FS 字段分隔符,程式中 FS=":" 等同命令行的 -F :
IGNORECASE 是否忽略大小寫,true 時比對不分大小寫(CentOS 6.5 上未測通)
NF 字段數,對應當前行的字段數量
NR 記錄數,對應當前行號
OFS 輸出字段分隔符(預設為一個空格)
ORS 輸出記錄分隔符(預設為換行符)
# FS 需在 BEGIN 中指定
BEGIN{ FS=":" } { print $1 }
$ awk -f sc.awk pass2.log
root
bin
daemon
# NF 與 NR
{ print NR " totall fileds" NF }
END{ print "line numbers:" NR }
# 注意:END 中無法取得字段數 NF
# OFS 與 ORS
$ awk -F : 'BEGIN{OFS="|";ORS=" LinEnd\n"}{print $1, $2;}' pass.log
root|x LinEnd
bin|x LinEnd
daemon|x LinEnd
注意:{print $1, $2} 必須用逗號連接;若寫成 {print $1 $2},OFS 會失效,因為空白在 awk 中本身就是字串連接符。
awk 'BEGIN{ commands } pattern{ commands } END{ commands }'
第一步:執行 BEGIN{} 中的語句;
第二步:從檔案或標準輸入讀取一行,執行 pattern{} 區塊;逐行掃描,從第一行到
最後一行重複此過程,直到讀完;
第三步:讀到輸入流末尾時,執行 END{} 區塊。
BEGIN 於讀取前執行,常用於變量初始化、輸出表頭;END 於讀取後執行,常用於
匯總分析結果;pattern 區塊是最重要也最常被使用的部分,若未提供,預設執行
{ print },即印出每一行。
不同內建變量的作用域不盡相同,使用時要注意它在 awk 執行的哪個階段才可用。
if(表達式) {語句1} else if(表達式) {語句2} else {語句3}
$ vi nsc.awk
# test for "if.. else if.. else"
{
if(NR%2==0) { print $2 " evenline" }
else if (NR%3==0){ print $3 " thrirdline" }
else { print $NF " othersLine" }
}
$ awk -F : -f nsc.awk /etc/passwd
/bin/bash othersLine
x evenline
2 thrirdline
x evenline
/sbin/nologin othersLine
for 語法:for(變量;條件;表達式) {語句}
$ awk 'BEGIN{ total=0; for(i=0;i<=100;i++) total+=i; print total; }'
5050
while 語法:while(表達式) {語句}
$ awk 'BEGIN{ test=100; total=0; i=0; while(i<=test){ total+=i; i++; } print total; }'
5050
do..while 語法:do {語句} while(條件)
$ awk 'BEGIN{ total=0; i=0; do {total+=i;i++;} while(i<=100) print total; }'
5050
$ awk 'BEGIN{ total=0; i=1000; do {total+=i;i++;} while(i<=100) print total; }'
1000
do..while 至少執行一次:先跑 do 中的內容再判斷條件,所以即使 i 一開始就不滿足 i<=100,仍會印出 1000。
break 直接跳出循環,continue 跳到下次循環,兩者都必須用在迴圈體內。
next 與 continue 相似,但它是跳過「本行」資料處理、直接處理下一行。
$ awk -F : '{if(NR>5&&NR<10)next; print NR, $1}' /etc/passwd
1 root
2 bin
3 daemon
4 adm
5 lp
10 uucp
11 operator ...
注意:next 只能出現在主體區塊,放在 BEGIN 或 END 中會報錯。
exit 會退出尚未執行的主體內容;若 END 中有內容則仍會執行。因此有三種情形:exit 在 BEGIN 中,直接跳到 END;exit 在主體中,直接跳到 END;exit 在 END 中,直接結束不再執行。
$ awk -F : '{if(NR>5){exit};print NR, $1}END{print "end"}' /etc/passwd
1 root ... 5 lp
end
$ awk -F : '{print "begin";exit;print "hh"}{print NR, $1}END{print "end"}' /etc/passwd
begin
end
用於記錄篩選:在 script 前加上 /express/,形式變為 '(/express/){awk 處理程式}'。
$ cat target.log
27.19.74.143 - - GET /static/image/common/faq.gif HTTP/1.1" 200 1127
110.52.250.126 - GET /data/cache/style_1_widthauto.css?y7a HTTP/1.1" 200 1292
...
110.44 - GET /static/image/common/logo.png HTTP/1.1" 200 4542 ← 最後一行 IP 格式異常
# 篩出含 gif 的行
$ awk '(/gif/){print $0}' target.log
# 篩出不含合法 IP 格式的異常行
$ awk --posix '!/([1-9][0-9]{0,2}\.){3}[1-9][0-9]{0,2}/{print $0}' target.log
110.44 - GET /static/image/common/logo.png HTTP/1.1" 200 4542
注意:在 gawk 4.0 以下版本中使用 {n,m} 這類區間正則,前面需加 --re-interval 或 --posix。
用於字段篩選:$n ~ 表示第 n 個字段滿足正則,$n !~ 表示不滿足,$0 則對整行篩選。
# 篩出用戶名長度為 4 的用戶
$ awk --posix -F : '$1~/^.{4}$/{print $1}' /etc/passwd
root sync halt mail uucp dbus vcsa abrt sshd
# 篩出用戶名長度不為 4 的用戶
$ awk --posix -F : '$1!~/^.{4}$/{print $1}' /etc/passwd
bin daemon adm lp shutdown operator games gopher ftp nobody ...
用在表達式中:正則可用於回傳 true/false 的表達式,同樣以 ~ 與 !~ 比對。
# 處理 /etc/passwd,匹配行號為二十多的行
$ awk --posix -F : '{if(NR ~ /^[2][0-9]$/)print NR,$1}' /etc/passwd
20 avahi-autoipd
21 abrt
22 haldaemon
...
29 sshd
總結:awk 的威力來自「BEGIN 初始化 + pattern 篩選 + 主體處理 + END 匯總」這套結構,再搭配位置變量、內建變量與正則,就能用一行命令完成過去需要寫腳本才能做的日誌分析。