awk是一个基于行的解释型的编程语言,主要用于文本分析及格式化输出。建议阅读文档AWK工作原理,AWK官方手册。
基本语法如下:
1 | |
其中:
单引号(‘’):避免shell对命令行转义,建议阅读shell引号问题;
BEGIN{commands} : 读输入文件之前执行的代码段,可选;
END{ commands }:读输入文件之后的代码段,可选;
pattern{ commands }:针对每一行的匹配pattern(支持正则),成功则执行commands;可以配置多组pattern{commands};
实例
比较并打印
1 | |
计算某列的和
1 | |
最后一列加1
1 | |
替换列为随机数
1 | |
命令中的1的解释:
awk evaluates the 1 as true and the prints the entire line by default, including a newline.
取子串并比较大小
1 | |
输出最长的行
1 | |
首列同则第2列相加排序输出
1 | |