leeboy的linux學習八awk指令碼

來源:互聯網
上載者:User

一、awk指令碼小程式,計算某一檔案夾中檔案的大小和。

#!/bin/awk -f#命名:file_tot.awk#功能:計算當前檔案夾中檔案大小和#使用方法:ls -l|./file_tot.awk#print a header firstBEGIN{print"this is the size of all files"print"fileName\t\tfilesize"print"----------------------------------"}#let's add the size of file(tot+=$5) {printf "%-24s%s\n",$8,tot}   #根據列印的頭長度來判斷靠左對齊空格長度#finished print an endEND{printf "\n"print "the total is : " totprint"------------the end!------------"}

 

#!/bin/awk -f  表示解析器的聲明

該指令碼和命令ls ../ -l | awk '(tot+=$5){printf "%-24s%s\n",$8,tot}' 執行效果一樣

使用執行個體如下:

 

二、當檔案中分隔字元不是空格時,需要使用指定分隔字元的awk指令碼:(如/etc/passwd中的分隔字元為“:”)

#!/bin/awk -f#命名:passwd.awk#功能:使用FS為awk指定分隔字元#print firstBEGIN{FS=":"#指定分隔字元}#根據分隔字元擷取指定欄位{printf "%-24s%s\n",$1,$6}#print the endEND{print "end of!"}

使用方法:./passwd.awk /etc/passwd

 

三、給awk指令碼傳入參數

#!/bin/awk -f#check on how many fields in the file#to call eg:./fieldcheck.awk MAX=8 FS=":" /etc/passwdBEGIN{print "start check!"}#NF:檔案中field域個數,FS:field分隔字元,NR已讀的記錄數{if(NF!=MAX) print "line" NR "dose not have" MAX "fields"}END{print "check end!"}

使用方法:./fieldcheck.awk MAX=8 FS=":" /etc/passwd

 

四、awk中的數組使用

#!/bin/awk -f#數組測試#to use eg:./arraytest.awk /dev/nullBEGIN{        record="123#879#567#wef#f4h";        print "數組長度:" split(record,myarray,"#")}END{        #for(i in myarray) {print myarray[i]} #無序輸出        for(i=1;i<=length(myarray);i++) print myarray[i]}

使用方法:./arraytest.awk /dev/null

/dev/null:代表空檔案裝置

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.