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] 和 -A[NUM]
,它们没有用,因为可能有搜索模式gef"和Start_pattern"之间的行数未知和End_pattern". grep
,sed
,awk
任何欢迎.最好是一个班轮.sed -n '/BEGIN/,/END/p' *
用于打印Search_pattern
之间的行,即"def"
和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 "
"}' 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"
"}/End_pattern/{if(b~/ef/){printf "%s",b};b=""}' file
说明:
# Append the current line plus a newline to b(uffer)
{b=b$0"
"}
# 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"
"}/End_pattern/{if(b~/ef/){printf "%s",b};b=""}' file
这篇关于grep 匹配一个模式的行,以及匹配前后的行直到不同的模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!