awk由main input循环组成,一个循环是一个例程,每个例程重复执行直到满足终止条件;
模式匹配
/^$/ {print “This is a blank line.”} --寻找空行并打印提示信息
~用于测试一个字段的正则表达式,!~表示不匹配
$5 ~ /MA/ { print $1 “, “ $6}
注释
以#开头,换行符结束,可在任何地方添加
条件语句
If ( condition) {
Action1
}
[ else
Action2
]
条件操作符
Expr ? action1 : action2
循环
While (condition) {
Action1
}
Do {
Action1
} While (condition)
For (expr1; expr2; expr3)
Action1
数组
Array[subscript] = value
Delete array[subscript]
下标可以是一个字符或一个数值,为稀疏数组
ARGV—命令行参数的数组,第1个下标为0,最后一个为ARGC – 1
ENVIRON –环境变量数组,
BEGIN {
For( x = 0; x < ARGC; ++x)
If( ARGV[x] !~ /^[0-9]+$/ ) { --寻找非数字
Print ARGV[x], “is not an integer.”
Exit 1
}
}
--打印当前所有系统变量
[oracle@ ~]$ more environ.awk
BEGIN {
for (env in ENVIRON)
print env "=" ENVIRON[env]
}
[oracle@ ~]$ awk -f environ.awk
TERM=vt100
….
SHELL=/bin/bash
字符串函数
gsub(r,s,t) –在字符串t中用s替换和正则表达式r匹配的所有字符串,若没有t则给出$0
sub(r,s,t) –
注:gsub()为global替换,而sub()只实现第一个位置
index(s,t) –返回t在s中的位置
length(s)
match(s,r) –如果正则表达式r在s中出现,则返回出现的起始位置
substr(s, p, n) – 返回s中从p开始最大长度为n的子串
tolower(s)/toupper(s)
split(string, array, separator) --将任何字符串string分解到数组array中
z = split($1, array, “ “)
For ( i = 1; I <= Z; i++)
Print I, array[i]
[oracle@ ~]$ cat test[1-3]
I am test1
I am test2
I am test3
[oracle@ ~]$ cat test
.so "test1"
this is 2nd line
.so test"2
this is 4rd line
.so test3
[oracle@ ~]$ cat gsub.awk --搜寻以.so开头的行,对其第2个参数去除”,接着执行cat $2,最后next
/^\.so/ {
gsub(/"/,"",$2)
system("cat " $2)
next
}
{ print }
[oracle@ ~]$ awk -f gsub.awk test
I am test1
this is 2nd line
I am test2
this is 4rd line
I am test3
内置函数
Getline
类似awk的next,即读取下一行数据;
返回值:1—读取成功 0—遇到文件末尾 -1—遇到错误
从文件读取数据
While ((getline < “data” ) > 0) –打印文件data的所有行
从输入中读取下一行并赋给变量(行数据没有分解成字段,因此NF不起作用)
Begin { printf “Enter your name:” getline name < “-“ print name}
从管道读取输入(将结果赋给$0)
[oracle@ ~]$ more user.awk --查看当前user的shell设置
BEGIN {
"who am i" | getline
name = $1
FS = ":"
}
name ~ $1 {print $7}
[oracle@ ~]$ awk -f user.awk /etc/passwd
/bin/bash
Close()
关闭打开的文件和管道
System()
返回被执行命令的退出状态,0为成功
[oracle@ ~]$ cat test2
first:second
one:two
[oracle@ ~]$ awk 'BEGIN { if(system("rm test2") == 0) print "test2 is dropped"}'
test2 is dropped
[oracle@ ~]$ ls test2
ls: test2: No such file or directory
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/15480802/viewspace-765617/ ,如需转载,请注明出处,否则将追究法律责任。