grep搜索+下一行


18

通过该grep命令,我找到了我需要的文本,如下所示:

grep 'C02' ~/temp/log.txt 现在,无论我在哪里找到所需的字符串,我都想在找到的字符串之后打印行。

例如,假设所需的文本是“ abc”,并且在第12行找到了abc,我也想打印第13行。


3
grep -A1 'abc' ~/temp/log.txt1行上下文的压脚提升的匹配-见Context Line Control手册(小节man grep
steeldriver

1
gnu grep使它变得容易;posix没有指定 -A标志
Jeff Schaller

1
嗨,欢迎来到Stack Exchange!在SE上,期望您在来这里寻求帮助之前进行一些基础研究。例如,搜索“ grep show next line”会在第一个结果中返回一个间接答案,在第二个结果中返回一个直接答案。您做了什么尝试来解决这个问题?
凌晨

Answers:


25

如果您使用的是Linux系统,则可以尝试:

grep -A1 "C02" ~/temp/log.txt


OPTIONS
       -A NUM, --after-context=NUM
              Print NUM lines of trailing context after matching lines.  Places a line containing -- between contiguous groups of matches.
       -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.

您也可以将awk用作:

awk '/C02/{print;getline;print}' ~/temp/log.txt

1
同时,sed -n '/C02/{N; p}' ~/temp/log.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.