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

 11 uwsgi_param  QUERY_STRING       $query_string;
 22 uwsgi_param  REQUEST_METHOD     $request_method;
 33 uwsgi_param  CONTENT_TYPE       $content_type;
 44 uwsgi_param  CONTENT_LENGTH     $content_length;
 55 uwsgi_param  REQUEST_URI        $request_uri;
 66 uwsgi_param  PATH_INFO          $document_uri;
 77 uwsgi_param  DOCUMENT_ROOT      $document_root;
 88 uwsgi_param  SERVER_PROTOCOL    $server_protocol;
 99 uwsgi_param  HTTPS              $https if_not_empty;
1010 uwsgi_param  REMOTE_ADDR        $remote_addr;
1111 uwsgi_param  REMOTE_PORT        $remote_port;
1212 uwsgi_param  SERVER_PORT        $server_port;
1313 uwsgi_param  SERVER_NAME        $server_name;

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

A参数:

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

B参数:

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

C参数:

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

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

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