CaTh
CaTh

Reputation: 21

grep line containing a pattern to line containing other pattern

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

Answers (3)

potong
potong

Reputation: 58371

This might work for you (GNU sed):

sed '/^"/h;G;/\n.*bbb/P;d' file

Upvotes: 0

Chris Seymour
Chris Seymour

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

janos
janos

Reputation: 124646

Something like this should do it:

sed -ne '/bbb/,/^"/ { /bbb/p; /^[^"]/p; }' file.txt

That is:

  • for the range of lines between matching /bbb/ and /^"/
  • if the line matches /bbb/ print it
  • if the line doesn't start with " print it
  • otherwise nothing else is printed

Upvotes: 2

Related Questions