awk是按照流来处理的,所以处理1-5G的文本数据相对还是可以的!
规定日志格式
$17 为domainname
$19 为request
$21 为响应状态码
应用1: 匹配统计F5日志中,含有某个域名的数量
可以按照以下方法来套
[root@CentOS-6-121 scripts]# awk -F: ‘$1=="root" {print $0}‘ /etc/passwd | wc -l 1
对以上进行改版,因为统计的时候利用了wc -l 进行了,现在不需要wc -l ,awk完成统计
[root@CentOS-6-121 scripts]# awk -F: -v n=0 ‘{if($1=="root") n++;} END{print n}‘ /etc/passwd 1
-v 可以指定变量,在 awk ‘‘中利用变量的时候直接使用,不需要"$n" 这个地方要区别shell
注意: 以下语句,默认不指定n变量的时候,虽然可以出结果,是因为在n++的时候会默认设置n为0,但是这样会出现bug,当没有匹配的时候,去大于n的时候就不是0而是空
[root@CentOS-6-121 scripts]# awk -F: ‘{if($1=="root") n++;} END{print n}‘ /etc/passwd 1
bug:
[root@CentOS-6-121 scripts]# awk -F: ‘{if($1=="rooot") n++;} END{print n}‘ /etc/passwd [root@CentOS-6-121 scripts]#
应用2: 使用shell中的变量和定义多变量 和逻辑运算符
&& 逻辑与
~ 匹配字符串
-v key1=value1 -v key2-values
原型:
awk -v t=0 -v domain="$domain" -v request="/main/detail" -v code=500 ‘$17==domain && $19 ~ request && $21 ==code {t++} END{print t}‘ access.log
0
测试语句:
[root@CentOS-6-121 scripts]# awk -F: ‘$1=="root" && $3==0 {print $0}‘ /etc/passwd root:x:0:0:root:/root:/bin/bash
注意:
判断匹配的方法:
1)$n~正则表达式
2)if($n~正则表示式) print $
如果你的awk中使用了 BEGIN语句,就一定要使用 if 不能使用模式匹配,否则报错
如:
报错:
[root@CentOS-6-121 scripts]# awk -F: ‘$1=="root" && $3==0 BEGIN{n=0} {n++} END{print n}‘ /etc/passwd
awk: $1=="root" && $3==0 BEGIN{n=0} {t++} END{print t}
awk: ^ syntax error
改为:
[root@CentOS-6-121 scripts]# awk -F: ‘BEGIN{n=0} {if($1 =="root" && $3==0)n++} END{print n}‘ /etc/passwd 1
应用3: awk中的数组
3 指定域名的
[root@shnh-bak001 f5-log]$ awk ‘$17 =="gold.dianpingfang.com" {++domain[$21]} END {for(k in domain) print k,domain[k]}‘ access.log
2
200 4498
301 2
500 15
302 321
304 2
本文出自 “崔德华运维打工从业路” 博客,请务必保留此出处http://cuidehua.blog.51cto.com/5449828/1771599
原文:http://cuidehua.blog.51cto.com/5449828/1771599