how can I find a matching pattern between two words using sed or awk

↘锁芯ラ 提交于 2020-01-06 19:56:32

问题


I want to search a pattern in paragraph that begins with word1 and end with word2 and print the first line of the paragraph if the pattern match, I am not sure if I can do it using grep for example if I have the following file and I am looking for aaa

Word1 this is paragraph number 1 
aaa
bbb
ccc
word2

Word1 this is paragraph number 2 
bbb
ccc
ddd
word2

the answer should be like that

Word1 this is paragraph number 1

回答1:


You can try this awk:

awk '/^Word1/{f=1;l="";hold=$0} /word2$/{f=0; if(l ~ /aaa/){print hold}} f{l = l RS $0}' file



回答2:


This might work for you (GNU sed):

sed -n '/^Word1/!b;:a;N;/^word2/M!ba;/^aaa/MP' file

Ignore any lines that do not begin Word1. Collect lines in the pattern space until a line beginning word2 or the end of the file. If a match is made then match also on the required string (in this case aaa). If a match is made print the first line and repeat.

EDIT: If paragraphs can end in other words i.e. word3, use this:

sed -n '/^Word1/!b;:a;N;/^$/Mb;/^word2/M!ba;/^aaa/MP' file



回答3:


This is the simple, idiomatic awk solution:

$ awk -v RS= -F'\n' '/^Word1.*aaa.*word2$/{print $1}' file
Word1 this is paragraph number 1

If that doesn't do what you want then edit your question to clarify your requirements.




回答4:


Try this one liner AWK:

 awk '/Word1/{l=$0;flag=1;next}/word2/{flag=0}flag && $0 ~ /aaa/ && !c{print l; c++}' file

Input:

Word1 this is paragraph number 1 
aaa
aaa
bbb
aaa
word2

Word1 this is paragraph number 2 
bbb
ccc
ddd
word2

Output:

Word1 this is paragraph number 1



回答5:


A simple solution (that doesn't match exactly what you asked for):

awk -F'\n' -v RS= '/bbb/{print $1}' file

This skips finding Word1/Word2, and assumes that you have a blank line between records as in your example.

Of course, you could always force the blank line beforehand, with sed:

gsed 's/^Word1/\n&/' file | ...above...


来源:https://stackoverflow.com/questions/35335409/how-can-i-find-a-matching-pattern-between-two-words-using-sed-or-awk

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!