Extracting line matching a phrase and then the next lines after it

Hi all,

I was wondering if someone could tell me a way to extract from a file lines where you search for a phrase and then also extract the next X lines after it (i.e. take a block of text from the file)?

Example

{
    id=123
    time=10:00:00
    date=12/12/09

    {
     ........
    }
}

{
    id=123
    time=10:00:00
    date=12/12/09

    {
     ........
    }
}

If possible i want to extract the id, time and date block....

Also is there a way also to extract text between 2 tags? such as { and } in my example?

You can use grep -Ax if your grep support this option, awk or sed shell script, etc...
The answer and the solution depend on your required output.

Unfortunately I do not have the grep -A option as I am on older systems.

All i want is to extract the information, at this stage no formatting is required so:

id=123
time=10:00:00
date=12/12/09
<SPACE>
id=123
time=11:00:00
date=12/12/09

....

Try

awk '/id/{f=1}/date/{print $0 ORS;f=0}f' FILE
  1. Print id, and 2 lines following it.
sed -n '/id/,+2p' FILE
  • sed -n : suppress default print,
  • /id/ : match pattern 'id'
  • +2 : next 2 lines
  • p: print
  1. print from { to }
sed -n '/{/,/}/p' FILE
  • sed -n : suppress default print,
  • /{/,/}/ : match from { to }
  • p : print

But the 2nd one will print everything, as all your text is enclosed with { and }

This is the similar to

awk '/id/,/date/' FILE

however your solution don't insert blank line between record blocks :rolleyes: see OP requirement.

sed -n '/id/{p;n;p;n;G;p}' t1

This can print the 2 lines from id, and with blank line following as asked for...

But, giving two regex /id/,/date/ cannot satisfy OPs requirement as printing next X lines, if date comes before/after 2 lines...