怎么在Linux中使用awk命令

怎么在Linux中使用awk命令?針對(duì)這個(gè)問(wèn)題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問(wèn)題的小伙伴找到更簡(jiǎn)單易行的方法。

在建始等地區(qū),都構(gòu)建了全面的區(qū)域性戰(zhàn)略布局,加強(qiáng)發(fā)展的系統(tǒng)性、市場(chǎng)前瞻性、產(chǎn)品創(chuàng)新能力,以專(zhuān)注、極致的服務(wù)理念,為客戶(hù)提供成都網(wǎng)站制作、網(wǎng)站設(shè)計(jì) 網(wǎng)站設(shè)計(jì)制作按需求定制制作,公司網(wǎng)站建設(shè),企業(yè)網(wǎng)站建設(shè),高端網(wǎng)站設(shè)計(jì),成都營(yíng)銷(xiāo)網(wǎng)站建設(shè),成都外貿(mào)網(wǎng)站建設(shè)公司,建始網(wǎng)站建設(shè)費(fèi)用合理。

awk簡(jiǎn)介

awk其名稱(chēng)得自于它的創(chuàng)始人 Alfred Aho 、Peter Weinberger 和 Brian Kernighan 姓氏的首個(gè)字母。實(shí)際上 AWK 的確擁有自己的語(yǔ)言: AWK 程序設(shè)計(jì)語(yǔ)言 , 三位創(chuàng)建者已將它正式定義為“樣式掃描和處理語(yǔ)言”。它允許您創(chuàng)建簡(jiǎn)短的程序,這些程序讀取輸入文件、為數(shù)據(jù)排序、處理數(shù)據(jù)、對(duì)輸入執(zhí)行計(jì)算以及生成報(bào)表,還有無(wú)數(shù)其他的功能。

awk 是一種很棒的語(yǔ)言,它適合文本處理和報(bào)表生成,其語(yǔ)法較為常見(jiàn),借鑒了某些語(yǔ)言的一些精華,如 C 語(yǔ)言等。在 linux 系統(tǒng)日常處理工作中,發(fā)揮很重要的作用,掌握了 awk將會(huì)使你的工作變的高大上。 awk 是三劍客的老大,利劍出鞘,必會(huì)不同凡響。

使用方法

awk '{pattern + action}' {filenames}

盡管操作可能會(huì)很復(fù)雜,但語(yǔ)法總是這樣,其中 pattern 表示 AWK 在數(shù)據(jù)中查找的內(nèi)容,而 action 是在找到匹配內(nèi)容時(shí)所執(zhí)行的一系列命令?;ɡㄌ?hào)({})不需要在程序中始終出現(xiàn),但它們用于根據(jù)特定的模式對(duì)一系列指令進(jìn)行分組。 pattern就是要表示的正則表達(dá)式,用斜杠括起來(lái)。

awk語(yǔ)言的最基本功能是在文件或者字符串中基于指定規(guī)則瀏覽和抽取信息,awk抽取信息后,才能進(jìn)行其他文本操作。完整的awk腳本通常用來(lái)格式化文本文件中的信息。

通常,awk是以文件的一行為處理單位的。awk每接收文件的一行,然后執(zhí)行相應(yīng)的命令,來(lái)處理文本。

awk 的原理

通過(guò)一個(gè)簡(jiǎn)短的命令,我們來(lái)了解其工作原理。

[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
...............................................

 你將會(huì)見(jiàn)到/etc/passwd 文件的內(nèi)容出現(xiàn)在眼前?,F(xiàn)在,解釋 awk 做了些什么。調(diào)用 awk時(shí),我們指定/etc/passwd 作為輸入文件。執(zhí)行 awk 時(shí),它依次對(duì)/etc/passwd 中的每一行執(zhí)行 print 命令。

所有輸出都發(fā)送到 stdout,所得到的結(jié)果與執(zhí)行 cat /etc/passwd 完全相同。
現(xiàn)在,解釋{ print }代碼塊。在 awk 中,花括號(hào)用于將幾塊代碼組合到一起,這一點(diǎn)類(lèi)似于 C 語(yǔ)言。在代碼塊中只有一條 print 命令。在 awk 中,如果只出現(xiàn) print 命令,那么將打印當(dāng)前行的全部?jī)?nèi)容。
再次說(shuō)明, awk 對(duì)輸入文件中的每一行都執(zhí)行這個(gè)腳本。 

 怎么在Linux中使用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參數(shù):指定分隔符,可指定一個(gè)或多個(gè)

print 后面做字符串的拼接

下面通過(guò)幾實(shí)例來(lái)了解下awk的工作原理:

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

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

 實(shí)例二:已知test.txt文件內(nèi)容為:

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

請(qǐng)從該文件中過(guò)濾出'Poe'字符串與33794712,最后輸出的結(jié)果為:Poe 33794712

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

BEGIN 和 END 模塊

通常,對(duì)于每個(gè)輸入行, awk 都會(huì)執(zhí)行每個(gè)腳本代碼塊一次。然而,在許多編程情況中,可能需要在 awk 開(kāi)始處理輸入文件中的文本之前執(zhí)行初始化代碼。對(duì)于這種情況, awk 允許您定義一個(gè) BEGIN 塊。

因?yàn)?awk 在開(kāi)始處理輸入文件之前會(huì)執(zhí)行 BEGIN 塊,因此它是初始化 FS(字段分隔符)變量、打印頁(yè)眉或初始化其它在程序中以后會(huì)引用的全局變量的極佳位置。
awk 還提供了另一個(gè)特殊塊,叫作 END 塊。 awk 在處理了輸入文件中的所有行之后執(zhí)行這個(gè)塊。通常, END 塊用于執(zhí)行最終計(jì)算或打印應(yīng)該出現(xiàn)在輸出流結(jié)尾的摘要信息。

實(shí)例一:統(tǒng)計(jì)/etc/passwd的賬戶(hù)人數(shù)

[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{}里都是只有一個(gè)print,其實(shí)print只是一個(gè)語(yǔ)句,而action{}可以有多個(gè)語(yǔ)句,以;號(hào)隔開(kāi)。這里沒(méi)有初始化count,雖然默認(rèn)是0,但是妥當(dāng)?shù)淖龇ㄟ€是初始化為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

實(shí)例二:統(tǒng)計(jì)某個(gè)文件夾下的文件占用的字節(jié)數(shù)

[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運(yùn)算符

怎么在Linux中使用awk命令

awk 賦值運(yùn)算符:a+5;等價(jià)于: a=a+5;其他同類(lèi)

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

awk邏輯運(yùn)算符:

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

判斷表達(dá)式 a>2&&b>1為真還是為假,后面的表達(dá)式同理

awk正則運(yùn)算符:

[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

關(guān)系運(yùn)算符:

如: > < 可以作為字符串比較,也可以用作數(shù)值比較,關(guān)鍵看操作數(shù)如果是字符串就會(huì)轉(zhuǎn)換為字符串比較。兩個(gè)都為數(shù)字 才轉(zhuǎn)為數(shù)值比較。字符串比較:按照ascii碼順序比較。

[root@Gin scripts]# awk 'BEGIN{a="11";if(a>=9){print "ok"}}' #無(wú)輸出
[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 算術(shù)運(yùn)算符:

說(shuō)明,所有用作算術(shù)運(yùn)算符進(jìn)行操作,操作數(shù)自動(dòng)轉(zhuǎn)為數(shù)值,所有非數(shù)值都變?yōu)?。

[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語(yǔ)言一樣:a++是先賦值加++;++a是先++再賦值

三目運(yùn)算符 ?:

[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 內(nèi)置變量

怎么在Linux中使用awk命令

注:內(nèi)置變量很多,參閱相關(guān)資料

字段分隔符 FS

FS="\t" 一個(gè)或多個(gè) 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:]+]" 一個(gè)或多個(gè)空白空格,默認(rèn)的

[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="[" ":]+" 以一個(gè)或多個(gè)空格或:分隔

[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

字段數(shù)量 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

記錄數(shù)量 NR

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

RS 記錄分隔符變量
將 FS 設(shè)置成"\n"告訴 awk 每個(gè)字段都占據(jù)一行。通過(guò)將 RS 設(shè)置成"",還會(huì)告訴 awk每個(gè)地址記錄都由空白行分隔。

[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 正則

怎么在Linux中使用awk命令

 正則應(yīng)用

規(guī)則表達(dá)式

awk '/REG/{action} ' file,/REG/為正則表達(dá)式,可以將$0 中,滿足條件的記錄送入到:action 進(jìn)行處理

[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  ## 以分號(hào)作為分隔符,匹配第5個(gè)字段是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

布爾表達(dá)式

awk '布爾表達(dá)式{action}' file 僅當(dāng)對(duì)前面的布爾表達(dá)式求值為真時(shí), awk 才執(zhí)行代碼塊。

[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、循環(huán)和數(shù)組

條件語(yǔ)句
awk 提供了非常好的類(lèi)似于 C 語(yǔ)言的 if 語(yǔ)句。

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

使用 if 語(yǔ)句還可以將代碼:

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

轉(zhuǎn)換成:

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

循環(huán)結(jié)構(gòu)

我們已經(jīng)看到了 awk 的 while 循環(huán)結(jié)構(gòu),它等同于相應(yīng)的 C 語(yǔ)言 while 循環(huán)。 awk 還有"do...while"循環(huán),它在代碼塊結(jié)尾處對(duì)條件求值,而不像標(biāo)準(zhǔn) while 循環(huán)那樣在開(kāi)始處求值。

它類(lèi)似于其它語(yǔ)言中的"repeat...until"循環(huán)。以下是一個(gè)示例:
do...while 示例

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

與一般的 while 循環(huán)不同,由于在代碼塊之后對(duì)條件求值, "do...while"循環(huán)永遠(yuǎn)都至少執(zhí)行一次。換句話說(shuō),當(dāng)?shù)谝淮斡龅狡胀?while 循環(huán)時(shí),如果條件為假,將永遠(yuǎn)不執(zhí)行該循環(huán)。

for 循環(huán)

awk 允許創(chuàng)建 for 循環(huán),它就象 while 循環(huán),也等同于 C 語(yǔ)言的 for 循環(huán):

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

以下是一個(gè)簡(jiǎn)短示例:

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

此段代碼將打?。?/p>

iteration1
iteration2
iteration3
iteration4

break 和 continue

此外,如同 C 語(yǔ)言一樣, awk 提供了 break 和 continue 語(yǔ)句。使用這些語(yǔ)句可以更好地控制 awk 的循環(huán)結(jié)構(gòu)。以下是迫切需要 break 語(yǔ)句的代碼片斷:

while 死循環(huán)
while (1) {
print "forever and ever..."
}
while 死循環(huán) 1 永遠(yuǎn)代表是真,這個(gè) while 循環(huán)將永遠(yuǎn)運(yùn)行下去。

以下是一個(gè)只執(zhí)行十次的循環(huán):

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

這里, break 語(yǔ)句用于“逃出”最深層的循環(huán)。 "break"使循環(huán)立即終止,并繼續(xù)執(zhí)行循環(huán)代碼塊后面的語(yǔ)句。
continue 語(yǔ)句補(bǔ)充了 break,其作用如下:

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

這段代碼打印"iteration1"到"iteration21", "iteration4"除外。如果迭代等于 4,則增加 x并調(diào)用 continue 語(yǔ)句,該語(yǔ)句立即使 awk 開(kāi)始執(zhí)行下一個(gè)循環(huán)迭代,而不執(zhí)行代碼塊的其余部分。如同 break 一樣,

continue 語(yǔ)句適合各種 awk 迭代循環(huán)。在 for 循環(huán)主體中使用時(shí), continue 將使循環(huán)控制變量自動(dòng)增加。以下是一個(gè)等價(jià)循環(huán):

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

在while 循環(huán)中時(shí),在調(diào)用 continue 之前沒(méi)有必要增加 x,因?yàn)?for 循環(huán)會(huì)自動(dòng)增加 x。

數(shù)組

AWK 中的數(shù)組都是關(guān)聯(lián)數(shù)組,數(shù)字索引也會(huì)轉(zhuǎn)變?yōu)樽址饕?/p>

{
    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&hellip;in 輸出,因?yàn)閿?shù)組是關(guān)聯(lián)數(shù)組,默認(rèn)是無(wú)序的。所以通過(guò) for&hellip;in 得到是無(wú)序的數(shù)組。如果需要得到有序數(shù)組,需要通過(guò)下標(biāo)獲得。

數(shù)組的典型應(yīng)用

用 awk 中查看服務(wù)器連接狀態(tài)并匯總

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

統(tǒng)計(jì) web 日志訪問(wèn)流量,要求輸出訪問(wèn)次數(shù),請(qǐng)求頁(yè)面或圖片,每個(gè)請(qǐng)求的總大小,總訪問(wèn)流量的大小匯總

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 列為下標(biāo)的數(shù)組( $10 列為$7 列的大?。?,把他們大小累加得到
$7 每次訪問(wèn)的大小,后面的 for 循環(huán)有個(gè)取巧的地方, a 和 b 數(shù)組的下標(biāo)相同,所以一
條 for 語(yǔ)句足矣

常用字符串函數(shù)

怎么在Linux中使用awk命令

怎么在Linux中使用awk命令

字符串函數(shù)的應(yīng)用

替換

awk 'BEGIN{info="this is a test2010test!";gsub(/[0-9]+/,"!",info);print info}' this is a test!test!
在 info 中查找滿足正則表達(dá)式, /[0-9]+/ 用”!”替換,并且替換后的值,賦值給 info 未
給 info 值,默認(rèn)是$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 #如果查找到數(shù)字則匹配成功返回 ok,否則失敗,返回未找到

截取

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

分割

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,動(dòng)態(tài)創(chuàng)建數(shù)組 tA,awk for &hellip;in 循環(huán),是一個(gè)無(wú)序的循環(huán)。 并不是從數(shù)組下標(biāo)
1&hellip;n 開(kāi)始

關(guān)于怎么在Linux中使用awk命令問(wèn)題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒(méi)有解開(kāi),可以關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道了解更多相關(guān)知識(shí)。

文章題目:怎么在Linux中使用awk命令
分享網(wǎng)址:http://bm7419.com/article6/gegsog.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供微信小程序、App設(shè)計(jì)網(wǎng)頁(yè)設(shè)計(jì)公司、企業(yè)建站、小程序開(kāi)發(fā)、外貿(mào)網(wǎng)站建設(shè)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

小程序開(kāi)發(fā)