简介
awk是一个强大的文本分析工具,相对于grep的查找,sed的编辑,awk在其对数据分析并生成报告时,显得尤为强大。简单来说awk就是把文件逐行的读入,以空格为默认分隔符将每行切片,切开的部分再进行各种分析处理。
awk有3个不同版本: awk、nawk和gawk,未作特别说明,一般指gawk,gawk 是 AWK 的 GNU 版本。
awk其名称得自于它的创始人 Alfred Aho 、Peter Weinberger 和 Brian Kernighan 姓氏的首个字母。实际上 AWK 的确拥有自己的语言: AWK 程序设计语言 , 三位创建者已将它正式定义为“样式扫描和处理语言”。它允许您创建简短的程序,这些程序读取输入文件、为数据排序、处理数据、对输入执行计算以及生成报表,还有无数其他的功能。
使用方法
awk '{pattern + action}' {filenames}
常用命令
1. 以每行的空格为标记, 摘取每行的第一列
awk '{print $1}' /proc/modules
2. 显示/etc/passwd的账户
cat /etc/passwd |awk -F ':' '{print $1}'
3. 显示/etc/passwd的账户和账户对应的shell,而账户与shell之间以tab键分割
cat /etc/passwd |awk -F ':' '{print$1"\t"$7}'
4. 内置变量
ARGC 命令行参数个数
ARGV 命令行参数排列
ENVIRON 支持队列中系统环境变量的使用
FILENAME awk浏览的文件名
FNR 浏览文件的记录数
FS 设置输入域分隔符,等价于命令行 -F选项
NF 浏览记录的域的个数
NR 已读的记录数
OFS 输出域分隔符
ORS 输出记录分隔符
RS 控制记录分隔符
awk -F ':' '{print "filename:"FILENAME ",lines:" NR ",columns:" NF",linecontent:"$0}' /etc/passwd
filename:/etc/passwd,lines:1,columns:7,linecontent:root:x:0:0:root:/root:/bin/bash
5. 赋值方法
1) arg=`(命令)`
2) arg=$(命令)
6. 打印文件的行列
打印文件的第一列(域) : awk '{print $1}'/proc/modules
打印文件的前两列(域) : awk '{print$1,$2}' /proc/modules
打印完第一列,然后打印第二列 : awk '{print $1 $2}' /proc/modules
打印文件文件的总行数 : awk 'END{print NR}' /proc/modules
打印文件第一行 :awk 'NR==1{print}'/proc/modules
打印文件第二行第一列 :sed -n "2, 1p" /proc/modules | awk'{print $1}'
7. 编程
awk中的循环语句借鉴于C语言,支持while、do/while、for、break、continue
awk -F ':' 'BEGIN {count=0;} {name[count] = $1;count++;};END{for (i = 0; i < NR; i++) print i, name[i]}' /etc/passwd
8. 改变分隔符
awk 'BEGIN {FS=","} {print $0}' /tmp/test.log
BEGIN语句将FS赋值为逗号, 表示以逗号为分隔符来处理文件, print语句设置需要打印的域名
帮助信息
$ awk -h
awk: option requires an argument -- h
Usage: awk [POSIX or GNU style options] -f progfile [--]file ...
Usage: awk [POSIX or GNU style options] [--] 'program'file ...
POSIX options: GNUlong options: (standard)
-f progfile --file=progfile
-F fs --field-separator=fs
-v var=val --assign=var=val
Short options: GNUlong options: (extensions)
-b --characters-as-bytes
-c --traditional
-C --copyright
-d[file] --dump-variables[=file]
-e 'program-text' --source='program-text'
-E file --exec=file
-g --gen-pot
-h --help
-L [fatal] --lint[=fatal]
-n --non-decimal-data
-N --use-lc-numeric
-O --optimize
-p[file] --profile[=file]
-P --posix
-r --re-interval
-S --sandbox
-t --lint-old
-V --version
To report bugs, see node `Bugs' in `gawk.info', which is
section `Reporting Problems and Bugs' in the printedversion.
gawk is a pattern scanning and processing language.
By default it reads standard input and writes standardoutput.
Examples:
gawk '{ sum += $1 }; END { print sum }' file
gawk -F: '{ print $1 }' /etc/passwd
参考资料
http://www.gnu.org/software/gawk/manual/gawk.html
http://www.jb51.net/article/85921.htm
https://www.cnblogs.com/ggjucheng/archive/2013/01/13/2858470.html