grep匹配模式的行,以及匹配之前和之后直到不同模式的行 [英] grep lines matching a pattern, and the lines before and after the matching until different pattern
问题描述
Start_pattern
abc
d End_pattern
Start_pattern
abc
d
ef
ghij
klm
no End_pattern
Start_pattern
abc
def
hij End_pattern
Start_pattern
abc
dhi
jklm End_pattern
所需的输出:
要打印Start_pattern
之间的行,包括Search_pattern
End_pattern
包括开始和结束模式.
To print lines between Start_pattern
including Search_pattern
End_pattern
Start and End pattern inclusive.
Start_pattern
abc
d
ef
ghij
klm
no End_pattern
Start_pattern
abc
def
hij End_pattern
在上面的文件中,我要搜索"ef"
并在"Strat_pattern"
和"End_pattern"
之间打印行.
In above file i want to search for "ef"
and print lines between "Strat_pattern"
and "End_pattern"
.
- 尝试过
grep -B[NUM] and -A[NUM]
,因为可能会没有用 搜索模式"gef"和"Start_pattern"之间的行数未知 和"End_pattern". -
grep
,sed
和awk
任何欢迎的内容.最好是一支班轮. -
sed -n '/BEGIN/,/END/p' *
用于在Search_pattern
和End_pattern
之间打印行.但是我无法在Start_pattern
和"def"
之间打印行
- 存在多个文件,并出现了多次search_pattern
- have tried
grep -B[NUM] and -A[NUM]
which are not useful as there could be unknown number of lines between search pattern "gef" and "Start_pattern" and "End_pattern". grep
,sed
,awk
anything welcomed. preferentially one liner.sed -n '/BEGIN/,/END/p' *
works to print lines betweenSearch_pattern
which is"def"
andEnd_pattern
. but iam not able to print lines betweenStart_pattern
and"def"
- Multiple files present with multiple occurrences of search_pattern
推荐答案
使用gawk
,它支持多字符RS
:
gawk 'BEGIN{RS=ORS="End_pattern"}/ef/' file
输出:
Start_pattern
abc
d
ef
ghij
klm
no End_pattern
Start_pattern
abc
def
hij End_pattern
说明:
# Split records based on the End_pattern
BEGIN{RS=ORS="End_pattern"}
# Print records that contain the search term
/ef/
顺便说一句,出于美观的原因,您可能希望在输出末尾添加换行符:
Btw, for cosmetic reasons you might want to append a newline at the end out the output:
gawk 'BEGIN{RS=ORS="End_pattern"}/ef/;END{printf "\n"}' file
PS:虽然上述解决方案仅适用于gawk
,但也可以使用与POSIX兼容的简单awk
脚本来实现,这意味着它可以与任何awk
一起使用:
PS: While the above solution works with gawk
only, it is also possible to achieve that with a simple awk
script which is compatible to POSIX, meaning it works with any awk
:
awk '{b=b$0"\n"}/End_pattern/{if(b~/ef/){printf "%s",b};b=""}' file
说明:
# Append the current line plus a newline to b(uffer)
{b=b$0"\n"}
# Once End_pattern is found ...
/End_pattern/{
# Check if the buffer contains the search term
if(b~/ef/){
# Print the buffer when the term was found
printf "%s",b
}
# Clear the buffer
b=""
}
awk '{b=b$0"\n"}/End_pattern/{if(b~/ef/){printf "%s",b};b=""}' file
这篇关于grep匹配模式的行,以及匹配之前和之后直到不同模式的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!