Printing next two lines from a file after grepping a specific pattern

Hi

I have a file like

# vi require.txt
1,BANK,Read blocks that cycle.
yellow
Read blocks.
2,ACCOUNT,Finished
Red
Finished .
3,LOAN, pipe
white
pipe
4,PROFIT,Resolve.
black
Resolve

Am using like

cat require.txt | grep -w ACCOUNT

The output I get is

2,ACCOUNT,Finished

But i need the output as

2,ACCOUNT,Finished
Red
Finished .

I need to grep the next two lines from that file once the grep patterns is matched..

Please help :confused:

My fav for this is..

 
awk 'c-->0;$0~s{if(b)for(c=b+1;c>1;c--)print r[(NR-c+1)%b];print;c=a}b{r[NR%b]=$0}' b=0 a=2 s="ACCOUNT" require.txt

b is number of lines above pattern and a is number of line below the pattern s is the search pattern

If you have GNU grep

grep -A 2 ACCOUNT require.txt
1 Like
 sed -n "/ACCOUNT/{N;N;p;}" file
 
awk 'c-->0;$0~s{if(b)for(c=b+1;c>1;c--)print r[(NR-c+1)%b];print;c=a}b{r[NR%b]=$0}' b=0 a=2 s="ACCOUNT" require.txt

b is number of lines above pattern and a is number of line below the pattern s is the search pattern

Thanks this code works very fine :slight_smile:

awk '/ACCOUNT/{a=FNR}; (a>0 && FNR<=a+2){print}' file

Try

 awk '/ACCOUNT/ {L=3} L-->0' file
2,ACCOUNT,Finished
Red
Finished .
# vi require.txt 
1,BANK,Read blocks that cycle.
 yellow 
Read blocks.
 2,ACCOUNT,Finished 
Red 
Finished . 
3,LOAN, pipe 
white 
pipe 
4,PROFIT,Resolve. 
black 
Resolve
5,PROFITIABLE,Loss
orange
Loss
6,ACCOUNTANT,clerk
yellow
work

If i use the code
awk 'c-->0;$0~s{if(b)for(c=b+1;c>1;c--)print r[(NR-c+1)%b];print;c=a}b{r[NR%b]=$0}' b=0 a=2 s="ACCOUNT" require.txt

The output is
2,ACCOUNT,Finished
Red
Finished .
6,ACCOUNTANT,clerk
yellow
work

This grep all pattern relative to ACCOUNT like ACCOUNT and ACCOUNTANT are grepped..

Please suggest me a way to grep the exact pattern ACCOUNT alone from this file

change in script..

awk 'c-->0;$0~s{if(b)for(c=b+1;c>1;c--)print r[(NR-c+1)%b];print;c=a}b{r[NR%b]=$0}' b=0 a=2 s="\\\\<ACCOUNT\\\\>" require.txt

Try

awk '/,ACCOUNT,/ {L=3} L-->0' file 

Why don't you give a complete and consistent specificaton of your problem in the first place?