awk命令的使用实例

awk 数据过滤工具
awk 选项 ‘BEGIN{} {} END{}’ 文件数组

/正则/
$1~/正则/
$2!~/正则/
$1== >= > < <= !=
&& ||
print $3 //但愿打哪一列的数据bash

if(判断){}else{}

能登录用户,不能登录的用户 // /etc/passwd/里以:为分隔符,共7列
》=500 <500
awk -F: '条件{}' 文件
awk -F: '{if($7~/bash/){x++}{y++}}'
awk -F: 'if($3>=500){i++}else{j++}'
END{print i,j}


awk while(判断)服务器

统计文件里面root出现了多少次
root:test:hello:root
tom:/root:world:root分布式

日志【某个IP访问屡次】,192.168.4.1
test.mp3 某个歌曲被访问多少次
IP==地理位置【IP能够转换成物理位置】,哪一个地区访问的人比较多ide

NF 列数
1.思考模式: $1=root $2==root $3==root $4==root $NF==root i++
2.工具

$x="root" //精确匹配测试

i=1
while [ $i<= NF ]
do
$i==root && x++
let i++
done
echo $x日志

awk -F: '{
i=1;
while(i<=NF){
if($i=="root"){x++};
i++
}
} END{print x}' code

#awk -F: '{i=1;while(i<=NF){if($i=="root"){x++};i++}} END{print x}' times.txt
3排序

i=1
while [ $i<= NF ]
do
$i==root && x++
let i++
done
echo $x

awk 数组 【背】
公式 $1 $2 $3

wc -l /var/log/httpd/access_log //查看日志行数

0 /var/log/httpd/access_log

客户端
#yum -y install httpd-tools

#ab -c 1000 -n 10000 http://192.168.4.254/ //压力测试软件,再大就是×××软件了

DOS ×××【来自统一个IP】 拒绝服务×××2W 【模拟x人×××】,再有人访问,就会拒绝访问
DDOS ××× 【分布式拒绝服务×××】【目前无方法,惟一方法,增长带宽,服务器】
统计每个人访问的次数

awk 数组 变量能存多个值
a(ab 11 gg cc)
a[0]=ab
a[1]=tt

a[192.168.4.1]=11
a[192.168.4.2]=22
a[192.168.4.254]=33

for i in a 0 1 3
{
print a[i]
}

awk 'BEGIN{a[0]="ab";a[1]="tt";print a[0],a[1]}' //字母的话,必定要有“”

ab tt

awk 'BEGIN{a[0]=123;a[1]=456;print a[0],a[1]}'

123 456

awk 'BEGIN{a["a"]=123;a["b"]=456;print a["a"],a["b"]}' //下标能够是数字,也能够是字母

123 456

awk '{IP[$1]++}
END{for i in IP{print IP[i]}} //IP是数组【for循环多少次,取决于IP有多少个下角标】

' test.txt

awk '{IP[$1]++} END{for(i in IP){print i,IP[i]}}' /var/log/httpd/access_log //无特定的顺序

192.168.4.254 17
::1 389
192.168.4.1 20026

sort排序:-k2 按第二列排序 -n按数字排序 -r降序

awk '{IP[$1]++} END{for(i in IP){print IP[i],i}}' /var/log/httpd/access_log | sort -nr

20026 192.168.4.1
389 ::1
17 192.168.4.254

awk '{IP[$1]++} END{for(i in IP){print IP[i],i}}' /var/log/httpd/access_log | sort -n

17 192.168.4.254
389 ::1
20026 192.168.4.1

awk '{IP[$1]++} END{for(i in IP){print i,IP[i]}}' /var/log/httpd/access_log | sort -k2 -n

192.168.4.254 17
::1 389
192.168.4.1 20026

awk '{IP[$1]++} END{for(i in IP){print i,IP[i]}}' /var/log/httpd/access_log | sort -k2 -nr

192.168.4.1 20026::1 389192.168.4.254 17

相关文章
相关标签/搜索