Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Awk between two patterns with pattern in the middle

Hi i am looking for an awk that can find two patterns and print the data between them to a file only if in the middle there is a third patterns in the middle. for example:

Start
1
2
middle
3
End
Start
1
2
End

And the output will be:
Start
1
2
middle
3
End

I found in the web awk '/patterns1/, /patterns2/' path > text.txt but i need only output with the third patterns in the middle.

like image 268
Yo Al Avatar asked Aug 19 '13 17:08

Yo Al


People also ask

How do I print lines between two patterns?

The sed command will, by default, print the pattern space at the end of each cycle. However, in this example, we only want to ask sed to print the lines we need. Therefore, we've used the -n option to prevent the sed command from printing the pattern space. Instead, we'll control the output using the p command.

What does awk '{ print $2 }' mean?

awk '{ print $2; }' prints the second field of each line. This field happens to be the process ID from the ps aux output.

What is awk '{ print $3 }'?

txt. If you notice awk 'print $1' prints first word of each line. If you use $3, it will print 3rd word of each line.

What does awk '{ print NF }' do?

The “NF” AWK variable is used to print the number of fields in all the lines of any provided file. This built-in variable iterates through all the lines of the file one by one and prints the number of fields separately for each line.


1 Answers

And here is a solution without flags:

$ awk 'BEGIN{RS="End"}/middle/{printf "%s", $0; print RT}'  file
Start
1
2
middle
3
End

Explanation: The RS variable is the record separator, so we set it to "End", so that each Record is separated by "End".

Then we filter the Records that contain "middle", with the /middle/ filter, and for the matched records we print the current record with $0 and the separator with print RT

like image 56
user000001 Avatar answered Oct 20 '22 08:10

user000001