Linux – How to grep a section of a file in bash shell

greplinux

How can I "grep" the lines between an occurrence of some string1 and the (Nth) occurrence of some string2.

e.g.

if the file has line:

A
B
C
D
E

F
G
B
C
E

Q

I want to get the lines in bold (those that begin with a B and end with an E).

Can this be done using grep? or some other Unix command line tool?

Best Answer

grep is not well suited for this task, you need to go one tool "up":

sed -n '/^B/,/^E/p' infile

Output:

B
C
D
E
B
C
E

With regards to the Nth requirement, I think its easiest if you again advance one tool "up", namely awk:

awk '/^B/ { f = 1; n++ } f && n == wanted; /^E/ { f = 0 }' wanted=2 infile

Output:

B
C
E

The flag f will be set when /^B/ is encountered and unset when /^E/ occurs, much in the same way the sed notation works. n keeps a tally of how many blocks have passed and when f == 1 && n == wanted is true, the default block will be executed ({ print $0 }).

Related Question