注:本篇文章從馬哥linux視頻教程獲取,在其中加了些註釋,也加了一些實例,對其中比較重要的語句使用紅色字體
語法:
# awk [options] 'script' file1 file2, ...
# awk [options] 'pattern { action }' file1 file2, ...
awk處理時每次讀取一行數據,根據分隔符進行輸出處理。python中也有類似的語法,使用readlines()與split()進行每行每字段處理
一、awk的輸出:print、printf
print的使用格式:
print item1, item2, ...
要點:
1、各項目之間使用逗號隔開,而輸出時則以空白字符分隔;
2、輸出的item可以爲字符串或數值、當前記錄的字段(如$1)、變量或awk的表達式;數值會先轉換爲字符串,而後再輸出;
3、print命令後面的item可以省略,此時其功能相當於print $0,awk中的$0不同於shell腳本,此處指代整個字段,如果想輸出空白行,則需要使用print "";
例子:
# awk 'BEGIN { print "line one\nline two\nline three" }'
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 -F:
OFS="#"
FS=":"(我一直沒用成功)
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命令的使用格式:
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
四、輸出重定向
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.
subscript in array True if the array array has an element with the subscript subscript.
6.7 表達式間的邏輯關係符:
&&
||
6.8 條件表達式:
selector?if-true-exp:if-false-exp
if selector; then
if-true-exp
else
if-false-exp
fi
a=3
b=4
a>b?a is max:b ia max
6.9 函數調用:
function_name (para1,para2)
七 awk的模式:
awk 'program' input-file1 input-file2 ...
其中的program爲:
pattern { action }
pattern { action }
...
7.1 常見的模式類型:
1、Regexp: 正則表達式,格式爲/regular expression/
awk -F: '/^root/{print $7} ' /etc/passwd
2、expresssion: 表達式,其值非0或爲非空字符時滿足條件,如:$1 ~ /foo/ 或 $1 == "magedu",用運算符~(匹配)和!~(不匹配)。
awk -F: '$3 >=500{print $1,$3}' /etc/passwd
awk -F: '$7 !~ "bash$"{print $1,$7}' /etc/passwd
3、Ranges: 指定的匹配範圍,格式爲pat1,pat2
4、BEGIN/END:特殊模式,僅在awk命令執行前運行一次或結束前運行一次
awk -F: 'BEGIN{printf "%-10s%-10s%-20s\n","Username","ID","Shell"}{printf "%-10s%-10s%-20s\n",$1,$3,$7}END{print 'End of report'}' /etc/passwd
5、Empty(空模式):匹配任意輸入行;
7.2 常見的Action
1、Expressions:表達式(賦值表達式)
2、Control statements:控制語句(if,do while,for,)
3、Compound statements:
4、Input statements
5、Output statements
八 控制語句:
8.1 if-else
語法:if (condition) {then-body} else {[ else-body ]}
例子:
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
awk -F: -v sum=0 '{if ($3>=500) sum++}END{print sum}' /etc/passwd
註釋:當'if(condition){then-body}',當then-body是單語句時可以省略{}
8.2 while
語法: while (condition){statement1; statment2; ...}
awk -F: '{i=1;while (i<=3) {print $i;i++}}' /etc/passwd
awk -F: '{i=1;while (i<=NF) { if (length($i)>=4) {print $i}; i++ }}' /etc/passwd
8.3 do-while
語法: do {statement1, statement2, ...} while (condition)
awk -F: '{i=1;do {print $i;i++}while(i<=3)}' /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, ...}
awk -F: '$NF!~/^$/{BASH[$NF]++}END{for(A in BASH){printf "%15s:%i\n",A,BASH[A]}}' /etc/passwd
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 -v max=0 '{if ($3 == "score") next}{if ($3 >max) max=$3}END{print max}' info.txt
九 awk中使用數組
9.1 數組
array[index-expression]
數組下標從1開始
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]}'
另外一種方式:netstat -ant |grep ^tcp |awk '{print $NF}' |sort |uniq -c |sort -rn
每出現一被/^tcp/模式匹配到的行,數組S[$NF]就加1,NF爲當前匹配到的行的最後一個字段,此處用其值做爲數組S的元素索引;
awk '{counts[$1]++}; END {for(url in counts) print counts[url], url}' /var/log/httpd/access_log
用法與上一個例子相同,用於統計某日誌文件中IP地的訪問量
例子:在txt文件中取出每subject中最大的值
name subject score
tim math 96
tom english 87
tim english 98
harry chinese 79
harry math 99
susan chinese 90
susan math 87
awk '{if($3=="score")next}{if($3 >subject[$2])subject[$2]=$3}END{for(info in subject){print info,subject[info]}}' info.txt
9.2 刪除數組變量
從關係數組中刪除數組索引需要使用delete命令。使用格式爲:
delete array[index]
十、awk的內置函數
split(string, array [, fieldsep [, seps ] ])
功能:將string表示的字符串以fieldsep爲分隔符進行分隔,並將分隔後的結果保存至array爲名的數組中;數組下標爲從0開始的序列;
netstat -ant | awk '/:80\>/{split($5,clients,":");IP[clients[1]]++}END{for(i in IP){print IP[i],i}}' | sort -rn | head -50
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”。