您如何grep文件并获取接下来的5行


Answers:


216

你要:

grep -A 5 '19:55' file

来自man grep

Context Line Control

-A NUM, --after-context=NUM

Print NUM lines of trailing context after matching lines.  
Places a line containing a gup separator (described under --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 (described under --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
(described under --group-separator) between contiguous groups of matches.  
With the -o or --only-matching option,  this  has  no effect and a warning
is given.

--group-separator=SEP

Use SEP as a group separator. By default SEP is double hyphen (--).

--no-group-separator

Use empty string as a group separator.

2
哇哇哇。太感谢了。
PhillipMwaniki

如果有一种方法不将输出限制为一定数量的行,而是在匹配的行之后打印所有行,那就太好了。
马赛厄斯·布劳恩

4

一些awk版本。

awk '/19:55/{c=5} c-->0'
awk '/19:55/{c=5} c && c--'

当发现模式,设置c=5
如果c是真的,印刷和减少数量c


2

这是一个sed解决方案:

sed '/19:55/{
N
N
N
N
N
s/\n/ /g
}' file.txt
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.