Search string and print the above line and below lines?.

if the first string matches then print the previous line and current line and also print the following lines if the other string search matches.

Input
------

TranTime 2012 10 12
The Record starts here
Accountnumber: 4632473431274
TxnCode 323
TranID 329473242834
ccsdkcnsdncskd wdededadlksadksadaskdsakd
dadscczxczccc
Balance 2000.00
TranTime 2012 10 13
The Record starts here
Accountnumber: 5435478454
TxnCode 312
TranID 5634875438
Balance 4000.00
csdhcsdjcsdcsdcnskjcjsdkjsdj
TranTime 2012 10 15
The Record starts here
Accountnumber: 31231231232
TxnCode 212
sdjhcsdjcbsd csdmcndscndskc
TranID 6546754654
Balance 1000.00
Here is what i have tried so far. but no luck.

awk '{
if ($0 ~ /The Record starts here/)
	{
	print a;
	}
	{
	a = $0;
	}
else  
if ($0 ~ /TranID|Balance|Accountnumber/)
	{
	print;
	}
else
	{
	print "else"
	}
}'

Expected output.

TranTime 2012 10 12
The Record starts here
Accountnumber: 4632473431274
TranID 329473242834
Balance 2000.00
TranTime 2012 10 13
The Record starts here
Accountnumber: 5435478454
TranID 5634875438
Balance 4000.00
TranTime 2012 10 15
The Record starts here
Accountnumber: 31231231232
TranID 6546754654
Balance 1000.00

any help will be greatly appreciated.

Thanks.

gnu grep (ggrep on solaris) provides what you need.

What OS are you on

uname -a

AIX 6.1

try:

awk '/^The Record/{$0=p$0}/^TranTime/{p=$0"\n"}/The Record/||/^Accountnumber/||/^TranID/||/^Balance/ {print}' infile
1 Like

Thank you for your time. i will check.

cat input.file | awk '{ if ($0 ~ /Record|TranTime|TranID|Balance|Account/) print $0; }'
What about the command above?

Command above can be written.

awk '$0 ~ /Record|TranTime|TranID|Balance|Account/' infile

Command above can be written:

awk '/Record|TranTime|TranID|Balance|Account/' infile