如何搜索文件中的行并提取搜索行的上方和下方的行。
我的输入就像
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。
请帮忙
答案 0 :(得分: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.
答案 1 :(得分:3)
Grep可以选择在匹配前后立即显示行。下面命令行中的数字是匹配之后和之前要显示的相应行数。 E.g。
grep -A3 -B5 yoursearchpattern inputfilepattern
man grep对于选项的详细信息非常有用。
假设您有GNU grep,要检查您是否可以使用--version选项:
> grep --version
GNU grep 2.6.3