AIX下AWK语言的操作符
[plain] www.zhishiwu.com
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
--the end--