awk '{ code for each line }'
awk '{ code for each line } END { code for end }'
awk '/regex for each line/ { code for each line } END { code for end }'
awk 'BEGIN { code before start } /regex for each line/ { code for each line } END { code for end }'
awk '$1 ~ "hello"' 打印 $1 匹配正则表达式 "hello" 的行
awk -F ',' '{ ..... }' // 分隔符可以用 '' 或 "" 包起, 分隔符可以是多个字符
awk 'BEGIN {FS=","} {....}' // 不能用 " 作为分隔符
awk 'BEGIN {FS="[,: ]]} {....}' // 可以指定多个不同的列分隔符. 遇到任意一个都进行分隔
awk 'BEGIN {RS="\n"} {....}'
awk 'BEGIN {OFS="-"} {....}'
print "this string is : "$0
print "this string is : ",$0
print "this string is : " $0
FS, RS 分隔符
$0 当前整行, $1 首列, $x 第x列
NR : 行数 行号
FILENAME : 当前文件名, 注意如果用了管道或者从标准输入得到文本, 文件名将显示为 '-'
awk 变量不需要声明, 无类型, 使用变量时, 其类型取决于使用时的上下文.
支持 ++ -- + - * / %
运算符
赋值支持 = += -= *= /= %=
比较测试 > < >= <= == != && ||
正则 ~ 匹配 !~ 不匹配
if (conditional) {action1; action2;}
if (conditional) action1 else action2
conditional-expression ? action1 : action2;
while (conditional) actions
do actions while (conditional)
for (init; cond; inc/dec) actions
循环语句支持 break, continue,
exit
awk 中的数组类似与 js 中的 Object.
index 可以不连续, 可以是字符串, array 不需要声明 不需要初始化.
数组引用直接使用 array[index] 方式即可.
判断数组中某个 index 是否有值 : if (index in array) {print "exist"}
遍历 Array : for (eleIndex in array) actions 其中 eleIndex 是对应元素的下标. 访问元素需 array[eleIndex]
删除数组元素 : delete array[index]
可以使用 asort 函数对数组元素排序 :
The GNU Awk User’s Guide
Sed and Awk 101 Hacks
awk '{print $1}' INPUTFILE
以空格为分割, 打印输入的每行的第一列.
awk -F ',' '{print $2}'
指定以','作为分隔符, 打印输入的每行第二列.
awk 中使用 reg 过滤记录
BEGIN {
s=0
pat="("
}
{
if(FNR==NR) {
if(FNR==1) {
pat=pat "" $0
} else {
pat=pat "|" $0
}
} else {
if (FNR==1){
pat=pat ")"
}
if ($0 ~ pat) {
s+=1
}
}
}
END {
print s
}
如果输入是两个文件, FNR==NR 则是第一个文件的内容 否则是第二个文件
awk 变量的字符串链接用空格. 比如 s="hello"; s = s " world"
在 awk 中, 可以使用 Awk 变量作为正则表达式. 例如:
pattern = "(abc|def)";
if ($1 ~ pattern) {
do something
}
使用 awk 中的 match, 用正则捕获字符串.
gawk 'match($0, /reqId ([^,]+)/, arr) { print arr[1]}'