0

Lets say I have the following content in a text file

...
abc
123
qwerty
line0
...
line3
line10
max
....

How to I grep for abc and capture all lines after the match and stop at line that contains specific text, in this example max ?

Mr.SrJenea
  • 483
  • 1
  • 6
  • 21
  • 1
    Possible duplicate of [How to select lines between two patterns?](https://stackoverflow.com/questions/38972736/how-to-select-lines-between-two-patterns) – Sundeep Oct 14 '17 at 03:50

3 Answers3

2

You can use sed:

sed '/abc/,/max/!d'
  • ! is negation
  • d means delete
  • /addr1/,/addr2/ is an "address range"
  • The whole expression means "Delete the line unless it's between a line matching /abc/ and a line matching /max/".

Similarly in Perl:

perl -ne 'print if /abc/ .. /max/'
choroba
  • 231,213
  • 25
  • 204
  • 289
2

Even simpler than sed and my beloved Perl is awk.

awk '/abc/,/max/' filename
Andy Lester
  • 91,102
  • 13
  • 100
  • 152
0

Line range addressing is simple in sed/awk, but if you really need to use grep, this will work:

grep -Poz 'abc[^\0]*max' file

The -z flag makes grep treat the input as null-byte terminated lines, so assuming your input doesn't contain any \0 bytes, the above PCRE will select everything between abc and max.

randomir
  • 17,989
  • 1
  • 40
  • 55