Reputation: 1197
My details are lengthy, yet simple :) I have a file like following:
Iteration 1
blah blah
.
.
.
blah blah
pattern 1
detail 1
detail 2
blah blah
.
.
.
blah blah
Iteration 2
.
.
.
Iteration 10
blah blah
.
.
.
blah blah
pattern 1
detail 1
detail 2
blah blah
.
.
.
blah blah
(Some iterations do not have pattern 1
). In this example only iteration 1 and iteration 10 contain the pattern.
There is always 2 detail lines after my pattern (detail 1 and detail 2) in which I am interested.
What I need is to parse out the iteration number, pattern and details (if that specific iteration contains the pattern) something like this:
Iteration 1
pattern 1
detail 1
detail 2
Iteration 10
pattern 1
...
What I did is :
sed -n '/Iteration/H;/pattern 1/{N;N;x;G;p}' file
The problem:
My output is something like
Iteration 1
pattern 1
detail 1
detail 2
pattern 1
detail 1
detail 2
Iteration 2
Iteration 3
It prints out my pattern and details 2 times. It also prints out all of the iterations ( I want only the number of iterations being parsed out which include pattern).
Upvotes: 0
Views: 115
Reputation: 212464
If your file has no blank lines, use sed to preprocess by breaking the file up into records that are separated by blank lines:
sed '/Iteration/i\
\
' input | awk '/pattern/' RS=
Upvotes: 1
Reputation: 44063
Use
# v-- here
sed -n '/Iteration/h;/pattern 1/{N;N;x;G;p}' file
H
appends the current line to the hold buffer, h
replaces the hold buffer with it. You want the latter, or you'll have a lot of cruft assembled in later matching blocks -- which is then printed.
Upvotes: 1