Regex 如何在多行中使用grep命令?

Regex 如何在多行中使用grep命令?,regex,bash,shell,grep,solaris,Regex,Bash,Shell,Grep,Solaris,使用shell脚本,我正在寻找使grep命令执行以下两个选项之一的方法: a) 使用grep命令在文件中显示以下10行匹配;即,命令grep“pattern”file.txt将生成文件中具有该模式的所有行: patternrestoftheline patternrestofanotherline patternrestofanotherline ... 所以我在寻找这个: patternrestoftheline following line following line ...

使用shell脚本,我正在寻找使grep命令执行以下两个选项之一的方法:

a) 使用grep命令在文件中显示以下10行匹配;即,命令
grep“pattern”file.txt
将生成文件中具有该模式的所有行:

patternrestoftheline

patternrestofanotherline

patternrestofanotherline

...
所以我在寻找这个:

patternrestoftheline

following line

following line

...

until the tenth

patternrestofanotherline

following line

following line

...

until the tenth
b) 使用grep命令显示两个模式内的所有行,就像它们是限制一样

patternA restoftheline

anotherline

anotherline

...

patternB restoftheline
我不知道用另一个命令代替grep是否是更好的选择。 我目前正在使用一个循环来解决我的问题,但它是逐行的,所以处理超大文件需要花费太多的时间

我正在寻找在Solaris上工作的解决方案。
有什么建议吗?

对于您的第一项任务,请使用
grep
-A
(“之后”)选项:

grep -A 10 'pattern' file.txt 
第二个任务是典型的
sed
问题:

sed -ne '/patternA/,/patternB/p' file.txt 
在案例(a)中,如果模式出现在10行内,您预计会发生什么

无论如何,这里有一些awk脚本应该可以工作(但未经测试;我没有Solaris):


第二个问题也可以通过使用
sed

选项-A在Solaris上不工作,但se解决了问题grep-A不受Solaris默认/usr/bin/grep或/usr/xpg4/grep支持。这是GNU coreutils的一部分,可能安装在Solaris上,也可能不安装@Uwe-1对不起,那么您要么使用rici的awk解决方案,要么安装GNU coreutils。在Solaris上使用nawk,而不是awk-/usr/bin/awk是旧版本。
# pattern plus 10 lines
awk 'n{--n;print}/PATTERN/{if(n==0)print;n=10}'

# between two patterns
awk '/PATTERN1/,/PATTERN2/{print}'