Linux-grep

写在前面

排查问题使用最多的方法就是查日志,日志量少的单个服务查询不在这次的讨论里面, 如果需要查询的日志里面有大量的干扰数据,我们就需要使用到筛选。首选的筛选命令grep,grep xxxxxx run.log可以帮我们查询出run.log中所有的xxxxxx出现。然后在找到对应的traceid,再来一次grep查询整个调用链路。

问题

但是在使用过程中发现订单号123456出现的位置太多,每次都查出了很多无用的信息,而我的诉求是

  1. 在过滤的信息中,只显示最新的10条数据,搭配head 使用
grep 123456 run.log | head -10 # 显示最新的10条匹配数据
  1. 显示匹配行的行号
grep -n 123456 run.log # 显示行号
  1. 显示匹配行的相邻几行
grep -A 10 123456 run.log # 匹配123456所在的行,及之后的10行
grep -B 10 123456 run.log # 匹配123456所在的行,及之前的10行
grep -C10 123456 run.log # 匹配123456所在的行,及前后10行
  1. 查询匹配123456 and createOrder
grep 123456 run.log | grep createOrder
grep -e 123456 -e createOrder run.log
grep -E '123456|createOrder' run.log
  1. 模糊查询文件
grep 123456 run* # 查询当前目录下run开头的文件,含有123456的行
grep 123456 * # 查询当前目录下所有文件,含有123456的行
  1. 查询匹配出来的行有多少
grep -c 123456 run.log
  1. 其他
cat test.txt |grep hat$ # 输出以hat结尾的行内容
cat test.txt |grep ^u # 找出以u开头的行内容
cat test.txt |grep ^[^u] # 输出非u开头的行内容
grep 'linux' test.txt test2.txt # 从多个文件中查找关键词

顺便说一下cat和vi的对比,cat打开,vi编辑

原文地址:https://www.cnblogs.com/wangshuyu/p/12745971.html