0

I want to get all lines of a textfile following a certain grep match until I hit another, different grep match. But if there is another match after that, I want to show lines again. Example: My textfile looks similar to:

Pattern_A
line1
line2
Pattern_B
line3
line4
Pattern_A
line5
line6
Pattern_B
line7

Now I need a command, that outputs:

Pattern_A
line1
line2
Pattern_A
line5
line6

Thank you in advance!

  • I'm sure this must be a duplicate but I can't find it - awk '/Pattern_A/ {p=1} /Pattern_B/ {p=0} p' file – steeldriver Aug 18 '18 at 12:20
  • Thanks for the answer, but does this also allow RegEx, like the wildcard * ? – CrustyPeanut Aug 18 '18 at 12:27
  • Yes, you can put any supported regex between / and / - note that different awk implementations may support more or fewer extended regex features. Also not that * on its own is a quantifier not a wildcard in regex (don't confuse regular expressions with shell globs). – steeldriver Aug 18 '18 at 12:36
  • see also this cross site duplicate with various cases: How to select lines between two patterns? – Sundeep Aug 18 '18 at 12:37
  • With GNU grep: grep -Poz 'Pattern_A(\n.*?)+(?=Pattern_B\n)' file – Cyrus Aug 18 '18 at 14:57
1

With GNU sed:

sed -n '/Pattern_A/,/Pattern_B/{/Pattern_B/d;p}' file

Output:

Pattern_A
line1
line2
Pattern_A
line5
line6

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.