3

如何在文件中搜索行并提取搜索行的上方和下方的行。

我的输入就像

Tue Jun 26 14:59:46 2012
 Warning ffffffff act_msg_ctms_remove_from_pending_queue: deleting message 44817201 from the queue.
Tue Jun 26 14:59:46 2012
 Warning ffffffff Finishing processing record number 44817201
Tue Jun 26 14:59:46 2012
 Warning  5000000 activity_queue_manager_finish_cb: unknown activity 120.
Tue Jun 26 14:59:46 2012
 Warning ffffffff Activity State Machine priority (2) finished
Tue Jun 26 14:59:46 2012
 Warning ffffffff 
====================================================
Processing database file "INCOMING_MESSAGES" record number 47810234 from user "(unknown)"
Tue Jun 26 14:59:46 2012
 Warning ffffffff ACTIVITY data: rec_num (47810234) size (116) 
Tue Jun 26 14:59:46 2012
 Warning ffffffff activity status: ACT_SENT 
Tue Jun 26 14:59:46 2012
 Warning ffffffff MESSAGE body "MVT
QFA6673/26.VHQOS.BNE
EA0541
"
Tue Jun 26 14:59:46 2012
 Warning ffffffff Finishing processing record number 47810234
Tue Jun 26 14:59:46 2012
 Warning ffffffff Activity State Machine priority (1) finished
Tue Jun 26 14:59:46 2012
 Warning ffffffff 
End processing record number 47810234

==================================================== ==

我要求我的输出像

/

Tue Jun 26 14:59:46 2012
 Warning ffffffff MESSAGE body "MVT
QFA6673/26.VHQOS.BNE
EA0541"

/

我的搜索字符串是 MVT。

请帮忙

4

2 回答 2

5

赛前赛后三线

grep -C 3 pattern filename 

要更好地控制要为匹配显示的前后行数,请使用

grep -A (num of after) -B (num of lines before)  pattern filename

来自man grep

 -A NUM, --after-context=NUM
          Print NUM lines of trailing context after matching lines.  
          Places a line containing -- between contiguous groups of matches.

   -a, --text
          Process a binary file as if it were text; 
          this is equivalent to the --binary-files=text option.

   -B NUM, --before-context=NUM
          Print NUM lines of leading context before matching lines.  
          Places a line containing -- between contiguous groups of matches.

   -C NUM, --context=NUM
          Print NUM lines of output context.  
          Places a line containing -- between contiguous groups of matches.
于 2012-06-26T07:11:26.043 回答
3

Grep 可以选择在匹配之前和之后立即显示行。下面命令行中的数字是匹配之后和之前要显示的适当行数。例如

grep -A3 -B5 yoursearchpattern inputfilepattern

man grep 对于有关选项的详细信息很有用。

假设你有 GNU grep,检查你可以使用 --version 选项:

> grep --version
GNU grep 2.6.3
于 2012-06-26T07:11:08.503 回答