grep:找出匹配行和前后的行

问题详情

需要统计nginx的访问日志中在某个时间点之后的IP以及IP的出现次数。于是可以先根据时间定位到某个时间点,再将该时间点之后的IP提取出来,统计出现次数。

解决方法

grep时Linux下非常好用的文本处理工具,功能非常强大。

  • grep文档中的介绍
Context Line Control
   -A NUM, --after-context=NUM
          Print  NUM  lines  of  trailing  context  after  matching  lines.   Places  a line
          containing a group separator (--) between contiguous groups of matches.  With  the
          -o or --only-matching option, this has no effect and a warning is given.

   -B NUM, --before-context=NUM
          Print  NUM  lines  of  leading  context  before  matching  lines.   Places  a line
          containing a group separator (--) between contiguous groups of matches.  With  the
          -o or --only-matching option, this has no effect and a warning is given.

   -C NUM, -NUM, --context=NUM
          Print  NUM  lines  of  output context.  Places a line containing a group separator
          (--) between contiguous groups of matches.  With the -o or --only-matching option,
          this has no effect and a warning is given.
  • 翻译

    上下文控制
      -A NUM,--after-context=NUM
            打印出匹配到的行之后的NUM行。如果有多个匹配关键词而且间隔超过给定的NUM时,打印结果会在匹配行以及打印的NUM行后面一行加上---,
            再显示下一个结果。带上-o或者--only-matching option选项,就不会有效果了,而且会出现一个警告。
    
      -B NUM, --before-context=NUM
            打印出匹配到的行以及前面的NUM行。
    
     -C NUM, -NUM, --context=NUM
            打印出匹配行和它前后各n行。
    原文作者:whisshe
    原文地址: https://www.jianshu.com/p/2872446ec2af
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞