grep ABC之行匹配

grep和awk、sed一样,是linux最常用的几个工具之一。grep自行带的ABC三个参数在行匹配方面,非常有用。其中A(after)用于输出匹配行的后N行,B(before)用于输出匹配行的前N行,C(center)用于输出匹配行的前后各N行。具体示例如下:

  1 uwsgi_param  QUERY_STRING       $query_string;
  2 uwsgi_param  REQUEST_METHOD     $request_method;
  3 uwsgi_param  CONTENT_TYPE       $content_type;
  4 uwsgi_param  CONTENT_LENGTH     $content_length;
  5 uwsgi_param  REQUEST_URI        $request_uri;
  6 uwsgi_param  PATH_INFO          $document_uri;
  7 uwsgi_param  DOCUMENT_ROOT      $document_root;
  8 uwsgi_param  SERVER_PROTOCOL    $server_protocol;
  9 uwsgi_param  HTTPS              $https if_not_empty;
 10 uwsgi_param  REMOTE_ADDR        $remote_addr;
 11 uwsgi_param  REMOTE_PORT        $remote_port;
 12 uwsgi_param  SERVER_PORT        $server_port;
 13 uwsgi_param  SERVER_NAME        $server_name;

具体我有一文本内容如上所示,grep匹配后的结果如下所示:

A参数:

[root@api conf]# grep -A 3 'HTTPS' test.txt
  9 uwsgi_param  HTTPS              $https if_not_empty;
 10 uwsgi_param  REMOTE_ADDR        $remote_addr;
 11 uwsgi_param  REMOTE_PORT        $remote_port;
 12 uwsgi_param  SERVER_PORT        $server_port;

B参数:

[root@api conf]# grep -B 3 'HTTPS' test.txt
  6 uwsgi_param  PATH_INFO          $document_uri;
  7 uwsgi_param  DOCUMENT_ROOT      $document_root;
  8 uwsgi_param  SERVER_PROTOCOL    $server_protocol;
  9 uwsgi_param  HTTPS              $https if_not_empty;

C参数:

[root@api conf]# grep -C 3 'HTTPS' test.txt
  6 uwsgi_param  PATH_INFO          $document_uri;
  7 uwsgi_param  DOCUMENT_ROOT      $document_root;
  8 uwsgi_param  SERVER_PROTOCOL    $server_protocol;
  9 uwsgi_param  HTTPS              $https if_not_empty;
 10 uwsgi_param  REMOTE_ADDR        $remote_addr;
 11 uwsgi_param  REMOTE_PORT        $remote_port;
 12 uwsgi_param  SERVER_PORT        $server_port;

使用C参数时,和grep按如下命令的执行结果相同:

[root@api conf]# grep -3 'HTTPS' test.txt
  6 uwsgi_param  PATH_INFO          $document_uri;
  7 uwsgi_param  DOCUMENT_ROOT      $document_root;
  8 uwsgi_param  SERVER_PROTOCOL    $server_protocol;
  9 uwsgi_param  HTTPS              $https if_not_empty;
 10 uwsgi_param  REMOTE_ADDR        $remote_addr;
 11 uwsgi_param  REMOTE_PORT        $remote_port;
 12 uwsgi_param  SERVER_PORT        $server_port;




本站的发展离不开您的资助,金额随意,欢迎来赏!

You can donate through PayPal.
My paypal id: itybku@139.com
Paypal page: https://www.paypal.me/361way

  1. 本文目前尚无任何评论.
  1. 本文目前尚无任何 trackbacks 和 pingbacks.