手机版
你好,游客 登录 注册 搜索
背景:
阅读新闻

AWK使用详解

[日期:2013-09-03] 来源:Linux社区  作者:lanlian [字体:大 中 小]

三、awk的操作符
算术操作符:
-x: 负值
+x: 转换为数值;
x^y: x的y次幂
x**y: 次方
x*y: 乘法
x/y:除法
x+y:加法
x-y:减法
x%y:取余


赋值操作符:
=
+=
-=
*=
/=
%=
^=
**=
++
--
需要注意的是,如果某模式为=号,此时使用/=/可能会有语法错误,应以/[=]/替代;
布尔值
awk中,任何非0值或非空字符串都为真,反之就为假;
比较操作符

x < y    True if x is less than y.
x <= y  True if x is less than or equal to y.
x > y      True if x is greater than y.
x >= y    True if x is greater than or equal to y.
x == y    True if x is equal to y.
x != y      True if x is not equal to y.
x ~ y      True if the string x matches the regexp denoted by y.
x !~ y      True if the string x does not match the regexp denoted by y.
subscript in array  True if the array array has an element with the subscript subscript.
表达式间的逻辑关系符
&&
||


条件表达式:

selector?if-true-exp:if-false-exp


if selector; then
 if-true-exp
else
 if-false-exp
fi


a=3
b=4
a>b?a is max:b ia max
函数调用:
function_name (para1,para2)


四、awk的控制语句:
if-else
语法:if (condition) {then-body} else {[ else-body ]}
# awk '{if ($3==0) {print $1, "Adminitrator";} else { print $1,"Common User"}}' /etc/passwd
例子:
awk -F: '{if ($1=="root") print $1, "Admin"; else print $1, "Common User"}' /etc/passwd
awk -F: '{if ($1=="root") printf "%-15s: %s\n", $1,"Admin"; else printf "%-15s: %s\n", $1, "Common User"}' /etc/passwd
awk -F: -v sum=0 '{if ($3>=500) sum++}END{print sum}' /etc/passwd


while

语法: while (condition){statement1; statment2; ...}
awk -F: '{i=1;while (i<=3) {print $i;i++}}' /etc/passwd
awk -F: '{i=1;while (i<=NF) { if (length($i)>=4) {print $i}; i++ }}' /etc/passwd
awk '{i=1;while (i<=NF) {if ($i>=100) print $i; i++}}' hello.txt


hello.txt文件的内容为一堆随机数。


do-while 至少执行一次循环体,不管条件满足与否

语法: do {statement1, statement2, ...} while (condition)
awk -F: '{i=1;do {print $i;i++}while(i<=3)}' /etc/passwd
awk -F: '{i=4;do {print $i;i--}while(i>4)}' /etc/passwd


for
语法: for ( variable assignment; condition; iteration process) { statement1, statement2, ...}
awk -F: '{for(i=1;i<=3;i++) print $i}' /etc/passwd
awk -F: '{for(i=1;i<=NF;i++) { if (length($i)>=4) {print $i}}}' /etc/passwd


for循环还可以用来遍历数组元素:
语法: for (i in array) {statement1, statement2, ...}
awk -F: '$NF!~/^$/{BASH[$NF]++}END{for(A in BASH){printf "%15s:%i\n",A,BASH[A]}}' /etc/passwd


BASH[/bin/bash]++
BASH[/sbin/nologin]


BASH[/bin/bash]=1
BASH[/sbin/nologin]=2
BASH[/bin/sync]=1


/bin/bash: 1
/sbin/nologin: 2
/bin/sync: 1


case
语法:switch (expression) { case VALUE or /REGEXP/: statement1, statement2,... default: statement1, ...}


break 和 continue
常用于循环或case语句中


next
提前结束对本行文本的处理,并接着处理下一行;例如,下面的命令将显示其ID号为奇数的用户:
# awk -F: '{if($3%2==0) next;print $1,$3}' /etc/passwd

linux
相关资讯       awk  AWK使用  AWK详解 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款