awk notes
awk语法
awk 'pattern + { action}'
说明:
(1) 单引号’‘是为了与shell命令区分开来
(2) 大括号{}表示一个命令分组
(3) pattern表示一个过滤器, 命中了pattern的行才进行action处理
(4) action是处理动作
(5) 用#作为注释
pattern说明
显示hello.txt的第三行到第5行
cat hello.txt | awk 'NR==3, NR=5 { print $0; }'
显示包含hello的行
cat hello.txt | awk '/hello/'
显示长度大于3的行
cat hello.txt | awk 'length($0) > 3 { print NR, "--", $0 }'
内置变量
- FS – field seperator 默认是空格, 可以通过-F指定
- NR – 当前行号, 从1开始
- NF – number of field
4 $0 – 当前行的内容
5 $n – 当前行的第几条记录
内置函数
- gsub(r, s)
- index(s, t)
- length(s)
- match(s,r)
- split(s,a,fs)
- substr(s,p)
操作符
- 运算类似于C, 支持 +, -, *, /, %, ++, –, +=, -= 等诸多操作
- 判断类似于C, 支持 ==, !=, >, =>, ~(匹配于)
控制流程
- BEGIN与END, 本质上也是个pattern, BEGIN用于awk程序开始前做些初始化工作, END收尾 比如统计字符个数
awk '
BEGIN {
count = 0;
}
{
count += length($0);
}
END {
print "总字符个数为: ", count;
}
'
- 流程控制语句
- if(condition){}else{}
- while{}
- do{}while(condition);
- for(init;condition;step){}
- break/continue:如果有END,会执行END中的收尾工作
流程控制语句用法几乎与c相同。
与shell交互
- awk中使用shell中定义的变量:使用单引号即可;
#!/bin/bash
STR="hello"
echo | awk '{ print "'${STR}'" }'
- awk中使用shell命令:使用双引号,或者system命令
echo hello | awk '{
print $0 | "cat"
}'
echo | awk '{
system("date > date.txt")
}'
-
awk中的变量输出到shell: 没办法, 老实用文件
-
getline: awk里, 从文件读取变量到awk中
#!/bin/bash
echo | awk '{
while(getline < "date.txt") {
print $0;
}
}'