Reputation: 21
Say the input is:
">"1aaa
2
3
4
">"5bbb
6
7
">"8ccc
9
">"10ddd
11
12
I want this output (per example for the matching pattern "bbb"):
">"5bbb
6
7
I had tried with grep:
grep -A 2 -B 0 "bbb" file.txt > results.txt
This works. However, the number of lines between ">"5bbb
and ">"8ccc
are variable. Does anyone knows how to achieve that using Unix command line tools?
Upvotes: 0
Views: 119
Reputation: 58371
This might work for you (GNU sed):
sed '/^"/h;G;/\n.*bbb/P;d' file
Upvotes: 0
Reputation: 85775
With awk
you could simply using a flag like so:
$ awk '/^">"/{f=0}/bbb/{f=1}f' file
">"5bbb
6
7
You could also parametrize the pattern like so:
$ awk '/^">"/{f=0}$0~pat{f=1}f' pat='aaa' file
">"1aaa
2
3
4
Explanation:
/^">"/ # Regular expression that matches lines starting ">"
{f=0} # If the regex matched unset the print flag
/bbb/ # Regular expression to match the pattern bbb
{f=1} # If the regex matched set the print flag
f # If the print flag is set then print the line
Upvotes: 3
Reputation: 124646
Something like this should do it:
sed -ne '/bbb/,/^"/ { /bbb/p; /^[^"]/p; }' file.txt
That is:
/bbb/
and /^"/
/bbb/
print it"
print itUpvotes: 2