起步上台

我从netstat命令中提取了如下信息作为用例:

  1. $ cat netstat.txt
  2. Proto Recv-Q Send-Q Local-Address Foreign-Address State
  3. tcp 0 0 0.0.0.0:3306 0.0.0.0:* LISTEN
  4. tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN
  5. tcp 0 0 127.0.0.1:9000 0.0.0.0:* LISTEN
  6. tcp 0 0 coolshell.cn:80 124.205.5.146:18245 TIME_WAIT
  7. tcp 0 0 coolshell.cn:80 61.140.101.185:37538 FIN_WAIT2
  8. tcp 0 0 coolshell.cn:80 110.194.134.189:1032 ESTABLISHED
  9. tcp 0 0 coolshell.cn:80 123.169.124.111:49809 ESTABLISHED
  10. tcp 0 0 coolshell.cn:80 116.234.127.77:11502 FIN_WAIT2
  11. tcp 0 0 coolshell.cn:80 123.169.124.111:49829 ESTABLISHED
  12. tcp 0 0 coolshell.cn:80 183.60.215.36:36970 TIME_WAIT
  13. tcp 0 4166 coolshell.cn:80 61.148.242.38:30901 ESTABLISHED
  14. tcp 0 1 coolshell.cn:80 124.152.181.209:26825 FIN_WAIT1
  15. tcp 0 0 coolshell.cn:80 110.194.134.189:4796 ESTABLISHED
  16. tcp 0 0 coolshell.cn:80 183.60.212.163:51082 TIME_WAIT
  17. tcp 0 1 coolshell.cn:80 208.115.113.92:50601 LAST_ACK
  18. tcp 0 0 coolshell.cn:80 123.169.124.111:49840 ESTABLISHED
  19. tcp 0 0 coolshell.cn:80 117.136.20.85:50025 FIN_WAIT2
  20. tcp 0 0 :::22 :::* LISTEN

下面是最简单最常用的awk示例,其输出第1列和第4例,

  • 其中单引号中的被大括号括着的就是awk的语句,注意,其只能被单引号包含。
  • 其中的$1..$n表示第几例。注:$0表示整个行。
  1. $ awk '{print $1, $4}' netstat.txt
  2. Proto Local-Address
  3. tcp 0.0.0.0:3306
  4. tcp 0.0.0.0:80
  5. tcp 127.0.0.1:9000
  6. tcp coolshell.cn:80
  7. tcp coolshell.cn:80
  8. tcp coolshell.cn:80
  9. tcp coolshell.cn:80
  10. tcp coolshell.cn:80
  11. tcp coolshell.cn:80
  12. tcp coolshell.cn:80
  13. tcp coolshell.cn:80
  14. tcp coolshell.cn:80
  15. tcp coolshell.cn:80
  16. tcp coolshell.cn:80
  17. tcp coolshell.cn:80
  18. tcp coolshell.cn:80
  19. tcp coolshell.cn:80
  20. tcp :::22

我们再来看看awk的格式化输出,和C语言的printf没什么两样:

  1. $ awk '{printf "%-8s %-8s %-8s %-18s %-22s %-15s\n",$1,$2,$3,$4,$5,$6}' netstat.txt
  2. Proto Recv-Q Send-Q Local-Address Foreign-Address State
  3. tcp 0 0 0.0.0.0:3306 0.0.0.0:* LISTEN
  4. tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN
  5. tcp 0 0 127.0.0.1:9000 0.0.0.0:* LISTEN
  6. tcp 0 0 coolshell.cn:80 124.205.5.146:18245 TIME_WAIT
  7. tcp 0 0 coolshell.cn:80 61.140.101.185:37538 FIN_WAIT2
  8. tcp 0 0 coolshell.cn:80 110.194.134.189:1032 ESTABLISHED
  9. tcp 0 0 coolshell.cn:80 123.169.124.111:49809 ESTABLISHED
  10. tcp 0 0 coolshell.cn:80 116.234.127.77:11502 FIN_WAIT2
  11. tcp 0 0 coolshell.cn:80 123.169.124.111:49829 ESTABLISHED
  12. tcp 0 0 coolshell.cn:80 183.60.215.36:36970 TIME_WAIT
  13. tcp 0 4166 coolshell.cn:80 61.148.242.38:30901 ESTABLISHED
  14. tcp 0 1 coolshell.cn:80 124.152.181.209:26825 FIN_WAIT1
  15. tcp 0 0 coolshell.cn:80 110.194.134.189:4796 ESTABLISHED
  16. tcp 0 0 coolshell.cn:80 183.60.212.163:51082 TIME_WAIT
  17. tcp 0 1 coolshell.cn:80 208.115.113.92:50601 LAST_ACK
  18. tcp 0 0 coolshell.cn:80 123.169.124.111:49840 ESTABLISHED
  19. tcp 0 0 coolshell.cn:80 117.136.20.85:50025 FIN_WAIT2
  20. tcp 0 0 :::22 :::* LISTEN