Linux三劍客之awk命令

awk簡介

awk其名稱得自於它的創始人 Alfred Aho 、Peter Weinberger 和 Brian Kernighan 姓氏的首個字母。實際上 AWK 的確擁有本身的語言: AWK 程序設計語言 , 三位建立者已將它正式定義爲「樣式掃描和處理語言」。它容許您建立簡短的程序,這些程序讀取輸入文件、爲數據排序、處理數據、對輸入執行計算以及生成報表,還有無數其餘的功能。javascript

awk 是一種很棒的語言,它適合文本處理和報表生成,其語法較爲常見,借鑑了某些語言的一些精華,如 C 語言等。在 linux 系統平常處理工做中,發揮很重要的做用,掌握了 awk將會使你的工做變的高大上。 awk 是三劍客的老大,利劍出鞘,必會不一樣凡響。
java

使用方法

awk '{pattern + action}' {filenames}

儘管操做可能會很複雜,但語法老是這樣,其中 pattern 表示 AWK 在數據中查找的內容,而 action 是在找到匹配內容時所執行的一系列命令。花括號({})不須要在程序中始終出現,但它們用於根據特定的模式對一系列指令進行分組。 pattern就是要表示的正則表達式,用斜槓括起來。linux

awk語言的最基本功能是在文件或者字符串中基於指定規則瀏覽和抽取信息,awk抽取信息後,才能進行其餘文本操做。完整的awk腳本一般用來格式化文本文件中的信息。web

一般,awk是以文件的一行爲處理單位的。awk每接收文件的一行,而後執行相應的命令,來處理文本。面試

awk 的原理

經過一個簡短的命令,咱們來了解其工做原理。
正則表達式

[root@Gin scripts]# awk '{print $0}' /etc/passwd
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
.....................................................

[root@Gin scripts]# echo hhh|awk '{print "hello,world"}'
hello,world

[root@Gin scripts]# awk '{print "hiya"}' /etc/passwd
hiya
hiya
hiya
hiya
...............................................

你將會見到/etc/passwd 文件的內容出如今眼前。如今,解釋 awk 作了些什麼。調用 awk時,咱們指定/etc/passwd 做爲輸入文件。執行 awk 時,它依次對/etc/passwd 中的每一行執行 print 命令。apache

全部輸出都發送到 stdout,所獲得的結果與執行 cat /etc/passwd 徹底相同。
如今,解釋{ print }代碼塊。在 awk 中,花括號用於將幾塊代碼組合到一塊兒,這一點相似於 C 語言。在代碼塊中只有一條 print 命令。在 awk 中,若是隻出現 print 命令,那麼將打印當前行的所有內容。
再次說明, awk 對輸入文件中的每一行都執行這個腳本。
編程


$ awk -F":" '{ print $1 }' /etc/passwd
$ awk -F":" '{ print $1 $3 }' /etc/passwd
$ awk -F":" '{ print $1 " " $3 }' /etc/passwd
$ awk -F":" '{ print "username: " $1 "\t\tuid:" $3" }' /etc/passwd

-F參數:指定分隔符,可指定一個或多個數組

print 後面作字符串的拼接bash

下面經過幾實例來了解下awk的工做原理:

實例一:只查看test.txt文件(100行)內第20到第30行的內容(企業面試)

 

[root@Gin scripts]# awk '{if(NR>=20 && NR<=30) print $1}' test.txt    
20
21
22
23
24
25
26
27
28
29
30

 

實例二:已知test.txt文件內容爲:

[root@Gin scripts]# cat test.txt 
I am Poe,my qq is 33794712

請從該文件中過濾出'Poe'字符串與33794712,最後輸出的結果爲:Poe 33794712

[root@Gin scripts]# awk -F '[ ,]+' '{print $3" "$7}' test.txt 
Poe 33794712

BEGIN END 模塊

一般,對於每一個輸入行, awk 都會執行每一個腳本代碼塊一次。然而,在許多編程狀況中,可能須要在 awk 開始處理輸入文件中的文本以前執行初始化代碼。對於這種狀況, awk 容許您定義一個 BEGIN 塊。

由於 awk 在開始處理輸入文件以前會執行 BEGIN 塊,所以它是初始化 FS(字段分隔符)變量、打印頁眉或初始化其它在程序中之後會引用的全局變量的極佳位置。
awk 還提供了另外一個特殊塊,叫做 END 塊。 awk 在處理了輸入文件中的全部行以後執行這個塊。一般, END 塊用於執行最終計算或打印應該出如今輸出流結尾的摘要信息。

實例一:統計/etc/passwd的帳戶人數

[root@Gin scripts]# awk '{count++;print $0;} END{print "user count is ",count}' passwd
root:x:0:0:root:/root:/bin/bash
..............................................
user count is  27

count是自定義變量。以前的action{}裏都是隻有一個print,其實print只是一個語句,而action{}能夠有多個語句,以;號隔開。這裏沒有初始化count,雖然默認是0,可是穩當的作法仍是初始化爲0:

[root@Gin scripts]# awk 'BEGIN {count=0;print "[start] user count is ",count} {count=count+1;print $0} END{print "[end] user count is ",count}' passwd 
[start] user count is  0
root:x:0:0:root:/root:/bin/bash
...................................................................
[end] user count is  27

實例二:統計某個文件夾下的文件佔用的字節數

[root@Gin scripts]# ll |awk 'BEGIN {size=0;} {size=size+$5;} END{print "[end]size is ",size}'
[end]size is  1489

若是以M爲單位顯示:

[root@Gin scripts]# ll |awk 'BEGIN{size=0;} {size=size+$5;} END{print "[end]size is ",size/1024/1024,"M"}'    
[end]size is  0.00142002 M

 

awk運算符

awk 賦值運算符:a+5;等價於: a=a+5;其餘同類

[root@Gin scripts]# awk 'BEGIN{a=5;a+=5;print a}'
10

awk邏輯運算符:

[root@Gin scripts]# awk 'BEGIN{a=1;b=2;print (a>2&&b>1,a=1||b>1)}'
0 1

判斷表達式 a>2&&b>1爲真仍是爲假,後面的表達式同理

awk正則運算符:

[root@Gin scripts]# awk 'BEGIN{a="100testaa";if(a~/100/) {print "ok"}}'
ok
[root@Gin scripts]# echo|awk 'BEGIN{a="100testaaa"}a~/test/{print "ok"}' 
ok

關係運算符:

如: > < 能夠做爲字符串比較,也能夠用做數值比較,關鍵看操做數若是是字符串就會轉換爲字符串比較。兩個都爲數字 才轉爲數值比較。字符串比較:按照ascii碼順序比較

[root@Gin scripts]# awk 'BEGIN{a="11";if(a>=9){print "ok"}}' #無輸出
[root@Gin scripts]# awk 'BEGIN{a=11;if(a>=9){print "ok"}}'  
ok
[root@Gin scripts]# awk 'BEGIN{a;if(a>=b){print "ok"}}'
ok

awk 算術運算符:

說明,全部用做算術運算符進行操做,操做數自動轉爲數值,全部非數值都變爲0

[root@Gin scripts]# awk 'BEGIN{a="b";print a++,++a}'
0 2
[root@Gin scripts]# awk 'BEGIN{a="20b4";print a++,++a}'
20 22

這裏的a++ , ++a與javascript語言同樣:a++是先賦值加++;++a是先++再賦值

三目運算符 ?:

[root@Gin scripts]# awk 'BEGIN{a="b";print a=="b"?"ok":"err"}'
ok
[root@Gin scripts]# awk 'BEGIN{a="b";print a=="c"?"ok":"err"}'
err

 經常使用 awk 內置變量

 注:內置變量不少,參閱相關資料

字段分隔符 FS

FS="\t" 一個或多個 Tab 分隔

[root@Gin scripts]# cat tab.txt 
ww   CC        IDD
[root@Gin scripts]# awk 'BEGIN{FS="\t+"}{print $1,$2,$3}' tab.txt
ww   CC        IDD 

FS="[[:space:]+]" 一個或多個空白空格,默認的

[root@Gin scripts]# cat space.txt 
we are    studing awk now!
[root@Gin scripts]# awk -F [[:space:]+] '{print $1,$2,$3,$4,$5}' space.txt 
we are   
[root@Gin scripts]# awk -F [[:space:]+] '{print $1,$2}' space.txt 
we are

FS="[" ":]+" 以一個或多個空格或:分隔

[root@Gin scripts]# cat hello.txt 
root:x:0:0:root:/root:/bin/bash
[root@Gin scripts]# awk -F [" ":]+ '{print $1,$2,$3}' hello.txt 
root x 0

字段數量 NF

[root@Gin scripts]# cat hello.txt 
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin:888
[root@Gin scripts]# awk -F ":" 'NF==8{print $0}' hello.txt 
bin:x:1:1:bin:/bin:/sbin/nologin:888

記錄數量 NR

[root@Gin scripts]# ifconfig eth0|awk -F [" ":]+ 'NR==2{print $4}'  ## NR==2也就是取第2行
192.168.17.129

RS 記錄分隔符變量
FS 設置成"\n"告訴 awk 每一個字段都佔據一行。經過將 RS 設置成"",還會告訴 awk每一個地址記錄都由空白行分隔

[root@Gin scripts]# cat recode.txt 
Jimmy the Weasel
100 Pleasant Drive
San Francisco,CA 123456

Big Tony
200 Incognito Ave.
Suburbia,WA 64890
[root@Gin scripts]# cat awk.txt 
#!/bin/awk
BEGIN {
        FS="\n"
        RS=""
}
{
        print $1","$2","$3
}
[root@Gin scripts]# awk -f awk.txt recode.txt 
Jimmy the Weasel,100 Pleasant Drive,San Francisco,CA 123456
Big Tony,200 Incognito Ave.,Suburbia,WA 64890

OFS 輸出字段分隔符

[root@Gin scripts]# cat hello.txt 
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin:888
[root@Gin scripts]# awk 'BEGIN{FS=":"}{print $1","$2","$3}' hello.txt 
root,x,0
bin,x,1
[root@Gin scripts]# awk 'BEGIN{FS=":";OFS="#"}{print $1,$2,$3}' hello.txt 
root#x#0
bin#x#1

ORS 輸出記錄分隔符

[root@Gin scripts]# cat recode.txt 
Jimmy the Weasel
100 Pleasant Drive
San Francisco,CA 123456

Big Tony
200 Incognito Ave.
Suburbia,WA 64890
[root@Gin scripts]# cat awk.txt 
#!/bin/awk
BEGIN {
        FS="\n"
        RS=""
        ORS="\n\n"
}
{
        print $1","$2","$3
}
[root@Gin scripts]# awk -f awk.txt recode.txt 
Jimmy the Weasel,100 Pleasant Drive,San Francisco,CA 123456

Big Tony,200 Incognito Ave.,Suburbia,WA 64890

 awk 正則

 正則應用

規則表達式

awk '/REG/{action} ' file,/REG/爲正則表達式,能夠將$0 中,知足條件的記錄送入到:action 進行處理

[root@Gin scripts]# awk '/root/{print $0}' passwd ##匹配全部包含root的行
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin

[root@Gin scripts]# awk -F: '$5~/root/{print $0}' passwd  ## 以分號做爲分隔符,匹配第5個字段是root的行 
root:x:0:0:root:/root:/bin/bash

[root@Gin scripts]# ifconfig eth0|awk 'BEGIN{FS="[[:space:]:]+"} NR==2{print $4}'
192.168.17.129

布爾表達式
awk '布爾表達式{action}' file 僅當對前面的布爾表達式求值爲真時awk 才執行代碼塊。

[root@Gin scripts]# awk -F: '$1=="root"{print $0}' passwd 
root:x:0:0:root:/root:/bin/bash
[root@Gin scripts]# awk -F: '($1=="root")&&($5=="root") {print $0}' passwd 
root:x:0:0:root:/root:/bin/bash

 awk if、循環和數組

條件語句

awk 提供了很是好的相似於 C 語言的 if 語句。

{
        if ($1=="foo"){
                if($2=="foo"){
                        print "uno"
                }else{
                        print "one"
                }
        }elseif($1=="bar"){
                print "two"
        }else{
                print "three"
        }
}

使用 if 語句還能夠將代碼:

! /matchme/ { print $1 $3 $4 }

轉換成:

{
  if ( $0 !~ /matchme/ ) {
    print $1 $3 $4
  }
}

循環結構

咱們已經看到了 awk while 循環結構,它等同於相應的 C 語言 while 循環。 awk 還有"do...while"循環,它在代碼塊結尾處對條件求值,而不像標準 while 循環那樣在開始處求值。

它相似於其它語言中的"repeat...until"循環。如下是一個示例:
do...while 示例

{
    count=1do {
        print "I get printed at least once no matter what"
    } while ( count !=1 )
}

與通常的 while 循環不一樣,因爲在代碼塊以後對條件求值, "do...while"循環永遠都至少執行一次。換句話說,當第一次遇到普通 while 循環時,若是條件爲假,將永遠不執行該循環。

for 循環

awk 容許建立 for 循環,它就象 while 循環,也等同於 C 語言的 for 循環:

for ( initial assignment; comparison; increment ) {
    code block
}

如下是一個簡短示例:

for ( x=1;x<=4;x++ ) {
    print "iteration", x
}

此段代碼將打印:

iteration1
iteration2
iteration3
iteration4

break continue

此外,如同 C 語言同樣, awk 提供了 break continue 語句。使用這些語句能夠更好地控制 awk 的循環結構。如下是迫切須要 break 語句的代碼片段:

while 死循環
while (1) {
print "forever and ever..."
}
while 死循環 1 永遠表明是真,這個 while 循環將永遠運行下去。

如下是一個只執行十次的循環:

#break 語句示例
x=1
while(1) {
  print "iteration", x
  if ( x==10 ) {
    break
  }
  x++
}

這裏, break 語句用於「逃出」最深層的循環。 "break"使循環當即終止,並繼續執行循環代碼塊後面的語句。
continue 語句補充了 break,其做用以下:

x=1while (1) {
        if ( x==4 ) {
        x++
        continue
    }
    print "iteration", x
    if ( x>20 ) {
        break
    }
    x++
} 

這段代碼打印"iteration1""iteration21""iteration4"除外。若是迭代等於 4,則增長 x並調用 continue 語句,該語句當即使 awk 開始執行下一個循環迭代,而不執行代碼塊的其他部分。如同 break 同樣,

continue 語句適合各類 awk 迭代循環。在 for 循環主體中使用時, continue 將使循環控制變量自動增長。如下是一個等價循環:

for ( x=1;x<=21;x++ ) {
    if ( x==4 ) {
        continue
    }
    print "iteration", x
}

while 循環中時,在調用 continue 以前沒有必要增長 x,由於 for 循環會自動增長 x

數組

AWK 中的數組都是關聯數組,數字索引也會轉變爲字符串索引

{
    cities[1]=」beijing」
    cities[2]=」shanghai」
    cities[「three」]=」guangzhou」
    for( c in cities) {
        print cities[c]
    }
    print cities[1]
    print cities[「1」]
    print cities[「three」]
}

for…in 輸出,由於數組是關聯數組,默認是無序的。因此經過 for…in 獲得是無序的數組。若是須要獲得有序數組,須要經過下標得到。

數組的典型應用

awk 中查看服務器鏈接狀態並彙總

netstat -an|awk '/^tcp/{++s[$NF]}END{for(a in s)print a,s[a]}'
ESTABLISHED 1
LISTEN 20

統計 web 日誌訪問流量,要求輸出訪問次數,請求頁面或圖片,每一個請求的總大小,總訪問流量的大小彙總

awk '{a[$7]+=$10;++b[$7];total+=$10}END{for(x in a)print b[x],x,a[x]|"sort -rn -k1";print
"total size is :"total}' /app/log/access_log
total size is :172230
21 /icons/poweredby.png 83076
14 / 70546
8 /icons/apache_pb.gif 18608
a[$7]+=$10 表示以第 7 列爲下標的數組( $10 列爲$7 列的大小),把他們大小累加獲得
$7 每次訪問的大小,後面的 for 循環有個取巧的地方, a 和 b 數組的下標相同,因此一
條 for 語句足矣

經常使用字符串函數

字符串函數的應用

替換

awk 'BEGIN{info="this is a test2010test!";gsub(/[0-9]+/,"!",info);print info}' this is a test!test!
在 info 中查找知足正則表達式, /[0-9]+/ 用」!」替換,而且替換後的值,賦值給 info 未
給 info 值,默認是$0

查找

awk 'BEGIN{info="this is a test2010test!";print index(info,"test")?"ok":"no found";}'
ok #未找到,返回 0

匹配查找

awk 'BEGIN{info="this is a test2010test!";print match(info,/[0-9]+/)?"ok":"no found";}'
ok #若是查找到數字則匹配成功返回 ok,不然失敗,返回未找到

截取

awk 'BEGIN{info="this is a test2010test!";print substr(info,4,10);}'
s is a tes #從第 4 個 字符開始,截取 10 個長度字符串

分割

awk 'BEGIN{info="this is a test";split(info,tA," ");print length(tA);for(k in tA){print k,tA[k];}}' 4
4 test 1 this 2 is 3 a
#分割 info,動態建立數組 tA,awk for …in 循環,是一個無序的循環。 並非從數組下標
1…n 開始
相關文章
相關標籤/搜索