天天看點

awk詳解

awk: 報告生成器

是一種程式語言,對文檔資料的處理具有很強的功能。

   # awk [options] 'script' file1 file2, ...

   # awk [options] 'PATTERN { action }' file1 file2, ...

awk的輸出:

一、print

print的使用格式:

print item1, item2, ...

要點:

1、各項目之間使用逗号隔開,而輸出時則以空白字元分隔;

2、輸出的item可以為字元串或數值、目前記錄的字段(如$1)、變量或awk的表達式;數值會先轉換為字元串,而後再輸出;

3、print指令後面的item可以省略,此時其功能相當于print $0, 是以,如果想輸出空白行,則需要使用print "";

例子:

   # awk 'BEGIN { print "line one\nline two\nline three" }'

在/etc/passwd中以冒号為分隔符,取出第一、第三字段内容顯示:

   #awk -F: '{ print $1, $3 }' /etc/passwd

二、awk變量

2.1 awk内置變量之記錄變量:

FS: field separator,讀取檔案本時,所使用字段分隔符;

RS: Record separator,輸入文本資訊所使用的換行符;

OFS: Output Filed Separator:

ORS:Output Row Separator:

可以定義以什麼符号為分隔符。例如:

   # awk 'BEGIN{FS=":"}{print $1,$7}' /etc/passwd

2.2 awk内置變量之資料變量:

NR: The number of input records,awk指令所處理的記錄數;如果有多個檔案,這個數目會把處理的多個檔案中行統一計數;

NF:Number of Field,目前記錄的field個數;

FNR: 與NR不同的是,FNR用于記錄正處理的行是目前這一檔案中被總共處理的行數;

ARGV: 數組,儲存指令行本身這個字元串,如#awk '{print $0}' a.txt b.txt這個指令中,ARGV[0]儲存awk,ARGV[1]儲存a.txt;

ARGC: awk指令的參數的個數;

FILENAME: awk指令所處理的檔案的名稱;

ENVIRON:目前shell環境變量及其值的關聯數組;如:

   #awk 'BEGIN{print ENVIRON["PATH"]}'

2.3 使用者自定義變量

gawk允許使用者自定義自己的變量以便在程式代碼中使用,變量名命名規則與大多數程式設計語言相同,隻能使用字母、數字和下劃線,且不能以數字開頭。gawk變量名稱區分字元大小寫。

2.3.1 在腳本中指派變量

在gawk中給變量指派使用指派語句進行,例如:

   #awk 'BEGIN{var="variable testing";print var}'

2.3.2 在指令行中使用指派變量

gawk指令也可以在“腳本”外為變量指派,并在腳本中進行引用。例如,上述的例子還可以改寫為:

   #awk -v var="variable testing" 'BEGIN{print var}'

三、printf

使用格式:

printf format, item1, item2, ...

1、其與print指令的最大不同是,printf需要指定format;

2、format用于指定後面的每個item的輸出格式;

3、printf語句不會自動列印換行符;使用\n換行

format格式的訓示符都以%開頭,後跟一個字元;如下:

%c: 顯示字元的ASCII碼;

%d, %i:十進制整數;

%e, %E:科學計數法顯示數值;

%f: 顯示浮點數;

%g, %G: 以科學計數法的格式或浮點數的格式顯示數值;

%s: 顯示字元串;

%u: 無符号整數;

%%: 顯示%自身;

修飾符:

N: 顯示寬度;

-: 左對齊;

+:顯示數值符号;

   # awk -F: '{printf "%-15s %i\n",$1,$3}' /etc/passwd

     %-15s:表示所取的第一個字段的類型為字元串,15表示字元寬度

四、輸出重定向

   print items > output-file

   print items >> output-file

   print items | command

五:特殊檔案描述符:

   /dev/stdin:标準輸入

   /dev/sdtout: 标準輸出

   /dev/stderr: 錯誤輸出

   /dev/fd/N: 某特定檔案描述符,如/dev/stdin就相當于/dev/fd/0;

   # awk -F: '{printf "%-15s %i\n",$1,$3 > "/dev/stderr" }' /etc/passwd

六、awk的操作符:

6.1 算術操作符:

-x: 負值

+x: 轉換為數值;

x^y:

x**y: 次方

x*y: 乘法

x/y:除法

x+y:

x-y:

x%y:

6.2 字元串操作符:

隻有一個,而且不用寫出來,用于實作字元串連接配接;

6.3 指派操作符:

=

+=

-=

*=

/=

%=

^=

**=

++

--

注意:如果某模式為=号,此時使用/=/可能會有文法錯誤,應以/[=]/替代;

6.4 布爾值

awk中,任何非0值或非空字元串都為真,反之就為假;

6.5 比較操作符:

   x < yTrue if x is less than y.

   x <= yTrue if x is less than or equal to y.

   x > yTrue if x is greater than y.

   x >= yTrue if x is greater than or equal to y.

   x == yTrue if x is equal to y.

   x != yTrue if x is not equal to y.

   x ~ yTrue if the string x matches the regexp denoted by y.

   x !~ yTrue if the string x does not match the regexp denoted by y.

6.7 表達式間的邏輯關系符:

   &&

   ||

6.8 條件表達式:

selector?if-true-exp:if-false-exp

if selector; then

 if-true-exp

else

 if-false-exp

fi

6.9 函數調用:

function_name (para1,para2)

七 awk的模式:

awk 'program' input-file1 input-file2 ...

其中的program為:

pattern { action }

...

7.1 常見的模式類型:

1、Regexp: 正規表達式,格式為/regular expression/

2、expresssion: 表達式,其值非0或為非空字元時滿足條件,如:$1 ~ /foo/ 或 $1 == "magedu",用運算符~(比對)和!~(不比對)。

3、Ranges: 指定的比對範圍,格式為pat1,pat2

4、BEGIN/END:特殊模式,僅在awk指令執行前運作一次或結束前運作一次

5、Empty(空模式):比對任意輸入行;

7.2 常見的Action

1、Expressions:

2、Control statements

3、Compound statements

4、Input statements

5、Output statements

/正規表達式/:使用通配符的擴充集。

關系表達式:可以用下面運算符表中的關系運算符進行操作,可以是字元串或數字的比較,如$2>%1選擇第二個字段比第一個字段長的行。

模式比對表達式:

模式,模式:指定一個行的範圍。該文法不能包括BEGIN和END模式。

BEGIN:讓使用者指定在第一條輸入記錄被處理之前所發生的動作,通常可在這裡設定全局變量。

END:讓使用者在最後一條輸入記錄被讀取之後發生的動作。

八 控制語句:

8.1 if-else

文法:if (condition) {then-body} else {[ else-body ]}

取出/etc/passwd中以空格為分隔符取出第三個字段,如果其值為0,則該使用者為Adminitrator;否則,該使用者為Common User。

   # awk '{if ($3==0) {print $1, "Adminitrator";} else { print $1,"Common User"}}' /etc/passwd

取出/etc/passwd中以冒号為分隔符取出第一個字段,當字段為root時,顯示該使用者為Adminitrator,否則顯示該使用者為Common User。

   #awk -F: '{if ($1=="root") print $1, "Admin"; else print $1, "Common User"}' /etc/passwd

   #awk -F: '{if ($1=="root") printf "%-15s: %s\n", $1,"Admin"; else printf "%-15s: %s\n", $1, "Common User"}' /etc/passwd

統計/etc/passwd中uid号大于等于500的使用者有多少

   #awk -F: -v sum=0 '{if ($3>=500) sum++}END{print sum}' /etc/passwd

8.2 while

文法: while (condition){statement1; statment2; ...}

顯示/etc/passwd中的第一、二、三字段

   #awk -F: '{i=1;while (i<=3) {print $i;i++}}' /etc/passwd

顯示/etc/passwd中字元長度大于等于4的字段

   #awk -F: '{i=1;while (i<=NF) { if (length($i)>=4) {print $i}; i++ }}' /etc/passwd

顯示hello.txt中所有大于等于100的字段,其中hello.txt檔案的内容為一堆随機數。

   #awk '{i=1;while (i<=NF) {if ($i>=100) print $i; i++}}' hello.txt

8.3 do-while 至少執行一次循環體,不管條件滿足與否

文法: do {statement1, statement2, ...} while (condition)

   #awk -F: '{i=1;do {print $i;i++}while(i<=3)}' /etc/passwd

顯示/etc/passwd中的第四字段,當執行do完成後,後面的不滿足就不再繼續執行,因而隻顯示一次

   #awk -F: '{i=4;do {print $i;i--}while(i>4)}' /etc/passwd

8.4 for

文法: for ( variable assignment; condition; iteration process) { statement1, statement2, ...}

   #awk -F: '{for(i=1;i<=3;i++) print $i}' /etc/passwd

   #awk -F: '{for(i=1;i<=NF;i++) { if (length($i)>=4) {print $i}}}' /etc/passwd

for循環還可以用來周遊數組元素:

文法: for (i in array) {statement1, statement2, ...}

當/etc/passwd中最後一個字段不是空白時,顯示所有的最後一個字段以及對應的行數

#awk -F: '$NF!~/^$/{BASH[$NF]++}END{for(A in BASH){printf "%15s:%i\n",A,BASH[A]}}' /etc/passwd

顯示結果如:

/bin/bash: 13

/sbin/nologin: 22

/bin/sync: 1

8.5 case

文法:switch (expression) { case VALUE or /REGEXP/: statement1, statement2,... default: statement1, ...}

8.6 break 和 continue

常用于循環或case語句中

8.7 next

提前結束對本行文本的處理,并接着處理下一行;例如,下面的指令将顯示其ID号為奇數的使用者:

   # awk -F: '{if($3%2==0) next;print $1,$3}' /etc/passwd

九 awk中使用數組

9.1 數組

array[index-expression]

index-expression可以使用任意字元串;需要注意的是,如果某資料組元素事先不存在,那麼在引用其時,awk會自動建立此元素并初始化為空串;是以,要判斷某資料組中是否存在某元素,需要使用index in array的方式。

要周遊數組中的每一個元素,需要使用如下的特殊結構:

for (var in array) { statement1, ... }

其中,var用于引用數組下标,而不是元素值;

   #netstat -ant | awk '/^tcp/ {++S[$NF]} END {for(a in S) print a, S[a]}'

每出現一被/^tcp/模式比對到的行,數組S[$NF]就加1,NF為目前比對到的行的最後一個字段,此處用其值做為數組S的元素索引;

   #awk '{counts[$1]++}; END {for(url in counts) print counts[url], url}' /var/log/httpd/access_log

用法與上一個例子相同,用于統計某日志檔案中IP地的通路量

9.2 删除數組變量

從關系數組中删除數組索引需要使用delete指令。使用格式為:

delete  array[index]

十、awk的内置函數

split(string, array [, fieldsep [, seps ] ])

功能:将string表示的字元串以fieldsep為分隔符進行分隔,并将分隔後的結果儲存至array為名的數組中;數組下标為從1開始的序列;

   # netstat -ant | awk '/:80\>/{split($5,clients,":");IP[clients[1]]++}END{for(i in IP){print IP[i],i}}' | sort -rn | head -50

上面指令過程:首先列出所有端口資訊,找出80端口所在行,然後在第五個字段以冒号為分隔符,儲存在clients變量中。是以clients[1]就表示所查找的ip,最後顯示ip次數和對應的ip,然後通過管道進行降序排序,最後取出前50個

   # netstat -tan | awk '/:80\>/{split($5,clients,":");ip[clients[4]]++}END{for(a in ip) print ip[a],a}' | sort -rn | head -50

   # df -lh | awk '!/^File/{split($5,percent,"%");if(percent[1]>=20){print $1}}'

表示将 df -lh所列出的資訊,除去以File開頭的行取第五段,以%為分隔符、儲存到percent中,然後判斷符合大于等于20的将其所在行的第一段顯示出來

length([string])

功能:傳回string字元串中字元的個數;

substr(string, start [, length])

功能:取string字元串中的子串,從start開始,取length個;start從1開始計數;

system(command)

功能:執行系統command并将結果傳回至awk指令

systime()

功能:取系統目前時間

tolower(s)

功能:将s中的所有字母轉為小寫

toupper(s)

功能:将s中的所有字母轉為大寫

十一、使用者自定義函數

自定義函數使用function關鍵字。格式如下:

function F_NAME([variable])

{

statements

}

函數還可以使用return語句傳回值,格式為“return value”。

Linux Web伺服器網站故障分析常用的指令

系統連接配接狀态篇:

1.檢視TCP連接配接狀态

   #netstat -nat |awk ‘{print $6}’|sort|uniq -c|sort -rn

   #netstat -n | awk ‘/^tcp/ {++S[$NF]};END {for(a in S) print a, S[a]}’ 或

   #netstat -n | awk ‘/^tcp/ {++state[$NF]}; END {for(key in state) print key,"\t",state[key]}’

   #netstat -n | awk ‘/^tcp/ {++arr[$NF]};END {for(k in arr) print k,"t",arr[k]}’

   #netstat -n |awk ‘/^tcp/ {print $NF}’|sort|uniq -c|sort -rn

   #netstat -ant | awk ‘{print $NF}’ | grep -v ‘[a-z]‘ | sort | uniq -c

2.查找請求數請20個IP(常用于查找攻來源):

   #netstat -anlp|grep 80|grep tcp|awk ‘{print $5}’|awk -F: ‘{print $1}’|sort|uniq -c|sort -nr|head -n20

   #netstat -ant |awk ‘/:80/{split($5,ip,":");++A[ip[1]]}END{for(i in A) print A[i],i}’ |sort -rn|head -n20

3.用tcpdump嗅探80端口的通路看看誰最高

   #tcpdump -i eth0 -tnn dst port 80 -c 1000 | awk -F"." ‘{print $1"."$2"."$3"."$4}’ | sort | uniq -c | sort -nr |head -20

4.查找較多time_wait連接配接

   #netstat -n|grep TIME_WAIT|awk ‘{print $5}’|sort|uniq -c|sort -rn|head -n20

5.找查較多的SYN連接配接

   #netstat -an | grep SYN | awk ‘{print $5}’ | awk -F: ‘{print $1}’ | sort | uniq -c | sort -nr | more

6.根據端口列程序

   #netstat -ntlp | grep 80 | awk ‘{print $7}’ | cut -d/ -f1

網站日志分析篇1(Apache):

1.獲得通路前10位的ip位址

   #cat access.log|awk ‘{print $1}’|sort|uniq -c|sort -nr|head -10

   #cat access.log|awk ‘{counts[$(11)]+=1}; END {for(url in counts) print counts[url], url}’

2.通路次數最多的檔案或頁面,取前20

   #cat access.log|awk ‘{print $11}’|sort|uniq -c|sort -nr|head -20

3.列出傳輸最大的幾個exe檔案(分析下載下傳站的時候常用)

   #cat access.log |awk ‘($7~/.exe/){print $10 " " $1 " " $4 " " $7}’|sort -nr|head -20

4.列出輸出大于200000byte(約200kb)的exe檔案以及對應檔案發生次數

   #cat access.log |awk ‘($10 > 200000 && $7~/.exe/){print $7}’|sort -n|uniq -c|sort -nr|head -100

5.如果日志最後一列記錄的是頁面檔案傳輸時間,則有列出到用戶端最耗時的頁面

   #cat access.log |awk ‘($7~/.php/){print $NF " " $1 " " $4 " " $7}’|sort -nr|head -100

6.列出最最耗時的頁面(超過60秒的)的以及對應頁面發生次數

   #cat access.log |awk ‘($NF > 60 && $7~/.php/){print $7}’|sort -n|uniq -c|sort -nr|head -100

7.列出傳輸時間超過 30 秒的檔案

   #cat access.log |awk ‘($NF > 30){print $7}’|sort -n|uniq -c|sort -nr|head -20

8.統計網站流量(G)

   #cat access.log |awk ‘{sum+=$10} END {print sum/1024/1024/1024}’

9.統計404的連接配接

   #awk ‘($9 ~/404/)’ access.log | awk ‘{print $9,$7}’ | sort

10. 統計http status

   #cat access.log |awk ‘{counts[$(9)]+=1}; END {for(code in counts) print code, counts[code]}'

   #cat access.log |awk '{print $9}'|sort|uniq -c|sort -rn

10.蜘蛛分析,檢視是哪些蜘蛛在抓取内容。

   #/usr/sbin/tcpdump -i eth0 -l -s 0 -w - dst port 80 | strings | grep -i user-agent | grep -i -E 'bot|crawler|slurp|spider'

網站日分析2(Squid篇)按域統計流量

   #zcat squid_access.log.tar.gz| awk '{print $10,$7}' |awk 'BEGIN{FS="[ /]"}{trfc[$4]+=$1}END{for(domain in trfc){printf "%st%dn",domain,trfc[domain]}}'

資料庫篇

1.檢視資料庫執行的sql

   #/usr/sbin/tcpdump -i eth0 -s 0 -l -w - dst port 3306 | strings | egrep -i 'SELECT|UPDATE|DELETE|INSERT|SET|COMMIT|ROLLBACK|CREATE|DROP|ALTER|CALL'

系統Debug分析篇

1.調試指令

   #strace -p pid

2.跟蹤指定程序的PID

   #gdb -p pid

本文轉自 宋鵬超 51CTO部落格,原文連結:http://blog.51cto.com/qidian510/1286551,如需轉載請自行聯系原作者