Skip to content
Advertisement

grep -A until a string

assuming that we have a file containing the following:

chapter 1 blah blah
blah num blah num
num blah num blah
...
blah num
chapter 2 blah blah

and we want to grep this file so we take the lines from chapter 1 blah blah to blah num (the line before the next chapter).

The only things we know are

  1. the stating string chapter 1 blah blah
  2. somewhere after that there is another line starting with chapter

a dummy way to do this is

grep -A <num> -i "chapter 1" <file>

with large enough <num> so the whole chapter will be in it.

Advertisement

Answer

This is easy to do with awk

awk '/chapter/ {f=0} /chapter 1/ {f=1} f' file
chapter 1 blah blah
blah num blah num
num blah num blah
...
blah num

It will print the line if flag f is true.
The chapter 1 and next chapter to changes the flag.


You can use range with awk but its less flexible if you have other stuff to test.

awk '/chapter 1/,/chapter [^1]/ {if (!/chapter [^1]/) print}' file
chapter 1 blah blah
blah num blah num
num blah num blah
...
blah num
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement