awk

awk是一个基于行的解释型的编程语言,主要用于文本分析及格式化输出。建议阅读文档AWK工作原理AWK官方手册
基本语法如下:

1
awk 'BEGIN{ commands } pattern{ commands } END{ commands }' files

其中:
单引号(‘’):避免shell对命令行转义,建议阅读shell引号问题
BEGIN{commands} : 读输入文件之前执行的代码段,可选;
END{ commands }:读输入文件之后的代码段,可选;
pattern{ commands }:针对每一行的匹配pattern(支持正则),成功则执行commands;可以配置多组pattern{commands};

实例

比较并打印

1
awk -F'\t' '$3 > 0 && $5 == "list"{print $3 "|" $5}' file

计算某列的和

1
awk -F' ' 'BEGIN{total=0}{total+=$1}END{print total}' file

最后一列加1

1
awk '{$NF=$NF+1;print $0}' file

替换列为随机数

1
awk '{$0=gensub(/ 160,/, " "int(rand()*60000)",", "g", $0)}1' file 

命令中的1的解释:

awk evaluates the 1 as true and the prints the entire line by default, including a newline.

取子串并比较大小

1
grep "adns_adm --reload-zone" adns_adm.log|awk '{a=substr($7,1,length($7)-2); if(a-1000>0) print $0}'

输出最长的行

1
awk ' { if ( length > x ) { x = length; y = $0 } }END{ print y }' file

首列同则第2列相加排序输出

1
2
awk -F ',' '{gsub(/"/, "", $1);gsub(/"/, "", $2); a[$1] += $2} END{for (i in a) print i, a[i]}' file|sort -k 2,2
注意:去除两列中的引号