日常工作需要用到,shell语句用于分析定位生产问题,本次做个记录
# 将日志先拷贝到当前目录
cp /tmp/Nginx.log .
本次目标是: 找出log中的404 500的报错
#使用管道取出相关日志
less nginx.log

通过/ 查询得知 状态码处于第9个字段
#使用 awk 筛选出第九个字段的全部内容
less nginx.log | awk '{print $9}'
对应结果集太多
# 使用sort排序 uniq -c 去重 统计
less nginx.log | awk '{print $9}'| sort | uniq -c

总有以上几种状态码,需要再次筛选
#使用 ~正则 匹配日志400和500状态相关的 $0打印所有行信息
less nginx.log | awk '$9~/500|404/{print $0}'

找出500错误时候的上下文,找出500错误的前两行 考察grep高级用法
可以使用grep -b
- -b 或 --byte-offset : 在显示符合样式的那一行之前,标示出该行第一个字符的编号。
- -B<显示行数> 或 --before-context=<显示行数> : 除了显示符合样式的那一行之外,并显示该行之前的内容。
grep -B 2 '500' nginx.log

统计前十的ip,分别打印ip和出现次数
首先查询到日志:cat nginx.log

通过日志分析的得知ip处于日志中第一个字段位置
#利用管道符,拼接awk分割,打印出的ip信息
cat nginx.log|awk {print $1}

管道符拼接
然后使用sort对结果进行排序
使用uniq -c 去统计次数
- -c或--count 在每列旁边显示该行重复出现的次数。

使用sort -nr 检查排序(以前十倒序排序)
- -n 依照数值的大小排序
- -r 以相反的顺序来排序
使用head -n 10 筛选数据只有 十行
