一、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:代表空檔案裝置