awk操作符
—————————————————————————————————————————————
= += *= / = %= ^ = 賦值操作符
? 條件表達操作符
|| && ! 並,與,非
< <= == != >> 關系操作符
+ - * / % ^ 算術操作符
+ + -- 前綴和後綴
——————————————————————————————————————————————
1.設置輸入域到域變量名
awk '{name=$1;color=$4; if(color ~/Yello/)print name" " is color "color}' grade.txt
P.Bunny is color Yello
2.賦值比較,通常在BEGIN部分賦值
a.在BEGIN中給變量名賦值
awk 'BEGIN {BASELINE="27 "} {if($6<BASELINE) print $0}' grade.txt
J.Lulu 06/99 48317 green 9 24 26
J.Troll 07/99 4842 Brown-3 12 26 26
b.在關系操作中使用實際數值
awk '{if($6 < 27) print $0}' grade.txt
J.Lulu 06/99 48317 green 9 24 26
J.Troll 07/99 4842 Brown-3 12 26 26
3.修改數值域取值
awk '{if($1=="M.Tansley") $5=$6-1; print $1, $6, $5, $7}' grade.txt
M.Tansley 40 39 44
J.Lulu 24 9 26
P.Bunny 35 12 28
J.Troll 26 12 26
L.Tansley 30 12 28
4.修改文本域
awk '{if($1=="J.Troll") ($1="J.Troll.L");print $1}' grade.txt
M.Tansley
J.Lulu
P.Bunny
J.Troll.L
L.Tansley
5.只顯示修改記錄
awk '{if( $1 == "J.Troll" ) {$1="J.Troll.L"; print $1}' grade.txt
awk: Syntax error
at line 1 of program << {if( $1 == "J.Troll" ... >>
context is
{if( $1 == "J.Troll" ) {$1="J.Troll.L"; print >>> $1} <<<
1 extra {
awk: illegal statement
at line 1 of program << {if( $1 == "J.Troll" ... >>
錯誤原因:少了一個“}”結束
awk '{if( $1 == "J.Troll" ) {$1="J.Troll.L"; print $1}}' grade.txt
J.Troll.L
6.創建新的域
awk 'BEGIN{ print "Name\t Difference"}
{if($6 < $7) {$8=$7-$6; print $1,$8}}' grade.txt
Name Difference
M.Tansley 4
J.Lulu 2
7.統計數據
awk '(tot += $6); END{print "Club student total points:" tot}' grade.txt
M.Tansley 05/99 48311 Green 8 40 44
J.Lulu 06/99 48317 green 9 24 26
P.Bunny 02/99 48 Yello 12 35 28
J.Troll 07/99 4842 Brown-3 12 26 26
L.Tansley 05/99 4712 Brown-2 12 30 28
Club student total points:155
8.文件長度相加
ls -l | awk ' /^[^d]/ {print $9"\t"$5} {tot += $5}
END {print "total KB:"tot}'
cat 0
cat_file.txt 28
data.f 356
delete_me_and_die 284
first2 61
grade.txt 235
info.txt 354
myfile 23
test.bak 225
test.sql 225
who.out 1998
wow 229
total KB:4018
查看當前目錄下的所有文件:
ls -l
total 24
-rw-r--r-- 1 xxxx group 0 Nov 19 10:12 cat
-rw-r--r-- 1 xxxx group 28 Nov 14 20:32 cat_file.txt
-rw-r--r-- 1 xxxx group 356 Nov 16 19:50 data.f
-rw-r--r-- 1 xxxx group 284 Nov 19 10:36 delete_me_and_die
-rwxr--r-- 1 xxxx group 61 Nov 8 09:15 first2
-rw-r--r-- 1 xxxx group 235 Nov 19 10:44 grade.txt
-rwxr--r-- 1 xxxx group 354 Nov 17 11:05 info.txt
-rwxr----- 1 xxxx group 23 Nov 7 19:12 myfile
-rwxr--r-- 1 xxxx group 225 Nov 15 18:08 test.bak
-rwxr--r-- 1 xxxx group 225 Nov 15 14:12 test.sql
-rw-r--r-- 1 xxxx group 1998 Nov 15 14:15 who.out
-rw-r--r-- 1 xxxx group 229 Nov 19 14:44 wow