Level 1
以如下信息作为用例:
$ cat netstat.txt
Proto Recv-Q Send-Q Local-Address Foreign-Address State
tcp 0 0 10.51.0.22:57972 tk-in-f188.1e100.n:5228 ESTABLISHED
tcp 0 0 10.51.0.22:53094 101.226.76.164:https CLOSE_WAIT
tcp 0 0 10.51.0.22:37514 101.227.160.102:https CLOSE_WAIT
tcp 0 0 10.51.0.22:37532 101.227.160.102:https ESTABLISHED
tcp 32 0 10.51.0.22:54788 220.181.7.190:https CLOSE_WAIT
tcp 1 0 10.51.0.22:45064 45.55.41.223:http CLOSE_WAIT
tcp6 1 0 ip6-localhost:40238 ip6-localhost:ipp CLOSE_WAIT
udp 0 0 10.51.0.22:37833 hkg07s29-in-f3.1e:https ESTABLISHED
下面是最简单最常用的awk示例,输出第1列和第4列:
$ awk '{print $1,$4}' netstat.txt
- 其中单引号中被大括号括着的就是awk的语句,其只能被单引号包含;
- 其中$1,$4分别表示第一列和第四列,$0表示整个行。
输出结果如下:
Proto Local-Address
tcp 10.51.0.22:57972
tcp 10.51.0.22:53094
tcp 10.51.0.22:37514
tcp 10.51.0.22:37532
tcp 10.51.0.22:54788
tcp 10.51.0.22:45064
tcp6 ip6-localhost:40238
udp 10.51.0.22:37833
awk的格式化输出和c语言的printf类似:
$ awk '{printf "%-8s %-8s %-8s %-18s\n",$1,$2,$3,$4}' netstat.txt
Proto Recv-Q Send-Q Local-Address
tcp 0 0 10.51.0.22:57972
tcp 0 0 10.51.0.22:53094
tcp 0 0 10.51.0.22:37514
tcp 0 0 10.51.0.22:37532
tcp 32 0 10.51.0.22:54788
tcp 1 0 10.51.0.22:45064
tcp6 1 0 ip6-localhost:40238
udp 0 0 10.51.0.22:37833
Level 2
过滤记录
下面的过滤条件为: 第1列的值为tcp && 第6列的值为CLOSE_WAIT
$ awk '$1=="tcp" && $6=="CLOSE_WAIT"' netstat.txt
tcp 0 0 10.51.0.22:53094 101.226.76.164:https CLOSE_WAIT
tcp 0 0 10.51.0.22:37514 101.227.160.102:https CLOSE_WAIT
tcp 32 0 10.51.0.22:54788 220.181.7.190:https CLOSE_WAIT
tcp 1 0 10.51.0.22:45064 45.55.41.223:http CLOSE_WAIT
如果需要输出表头,可以引入内建变量NR:
$ awk '$1=="tcp" && $6=="CLOSE_WAIT" || NR==1' netstat.txt
Proto Recv-Q Send-Q Local-Address Foreign-Address State
tcp 0 0 10.51.0.22:53094 101.226.76.164:https CLOSE_WAIT
tcp 0 0 10.51.0.22:37514 101.227.160.102:https CLOSE_WAIT
tcp 32 0 10.51.0.22:54788 220.181.7.190:https CLOSE_WAIT
tcp 1 0 10.51.0.22:45064 45.55.41.223:http CLOSE_WAIT
再加上格式化输出:
$ awk '$1=="tcp" && $6=="CLOSE_WAIT" || NR==1 {printf "%-8s %-20s %-20s %-20s\n",$1,$4,$5,$6}' netstat.txt
Proto Local-Address Foreign-Address State
tcp 10.51.0.22:53094 101.226.76.164:https CLOSE_WAIT
tcp 10.51.0.22:37514 101.227.160.102:https CLOSE_WAIT
tcp 10.51.0.22:54788 220.181.7.190:https CLOSE_WAIT
tcp 10.51.0.22:45064 45.55.41.223:http CLOSE_WAIT
内建变量
awk的一些内建变量:
内建变量 | 说明 |
---|---|
$0 | 当前记录(这个变量中存放着整个行的内容) |
$1~$n | 当前记录的第n个字段,字段间由FS分隔 |
FS | 输入字段分隔符,默认是空格或Tab |
OFS | 输出字段分隔符,默认是空格或Tab |
NF | 当前记录中字段个数,即列数 |
NR | 已经读出的记录数,即行号,从1开始,若有多个文件,该值不断累加 |
FNR | 当前记录数,与NR不同的是,该值为各个文件的行号 |
RS | 输入的记录分隔符,默认为换行符 |
ORS | 输出的记录分隔符,默认为换行符 |
FILENAME | 当前输入文件的名字 |
下面来看一下怎样使用这些内建变量吧!
如果要输出行号:
$ awk '$1=="tcp" && $6=="CLOSE_WAIT" || NR==1 {print NR,FNR,$1,$4,$5,$6}' netstat.txt
1 1 Proto Local-Address Foreign-Address State
3 3 tcp 10.51.0.22:53094 101.226.76.164:https CLOSE_WAIT
4 4 tcp 10.51.0.22:37514 101.227.160.102:https CLOSE_WAIT
6 6 tcp 10.51.0.22:54788 220.181.7.190:https CLOSE_WAIT
7 7 tcp 10.51.0.22:45064 45.55.41.223:http CLOSE_WAIT