-
IF條件判斷
文法一
if (表達式)
動作1
else
動作2
文法二
if (表達式) 動作1;else 動作2
#判斷boot分區可用容量小于20MB時報警,否則顯示OK
df |grep 'boot' |awk '{if($4<20000) print "Alart";else print "OK"}'
-
while循環
while (條件)
動作
例子:
x=1
while (i<10){
print $1
}
awk 'i=1{} BEGIN { while(i<=10) {++i;print i} }' test.txt
do
動作
while(條件)
awk 'BEGIN { do {++x;print x} while (x<=10) }' test.txt
-
for循環
for (變量; 條件;計數器)
動作
awk 'BEGIN {for(i=1;i<=10;i++) print i}' test.txt
awk 'BEGIN {for(i=10;i>=1;i--) print i}' test.txt
-
Break與continue
break 跳出循環
continue 終止目前循環
for (i=1;i<=10;i++) {
if (i=5)
continue
print i
break
-
函數
5.1 rand()函數
awk 'BEGIN{print rand();print srand();print srand()}' test.txt
5.2 gsub(x,y,z)函數
作用在字元串z中使用字元串y替換與正規表達式x相比對所有字串,z預設為$0
awk -F: 'gsub(/root/,"ccc",$0) {print $0}' /etc/passwd
ccc:x:0:0:ccc:/ccc:/bin/bash
5.3 sub(x,y,z)函數
作用在字元串z中使用字元串y替換與正規表達式x相比對的第一個字串,z預設為$0
awk -F: 'sub(/ccc/,"root",$0) {print $0}' /etc/passwd
5.4 length(z)函數
作用:顯示test.txt文檔中每行的字元長度:
awk '{print length()}' /usr/local/src/allen/test.txt
5.5 getline()函數
df -h | awk '{if(NF==1) {getline;print $3};if(NF==6) print $4}'