How to search word and get the line above it.

Hey all,

Could any one help me ...

I want to search the word and want the line above it.

eg. mytxt.log

My name is Jeevan.
240 is my address.

My name is Jhon.
390 is my address.
--------
i want to search "240" and want output as

My name is Jeevan.
240 is my address.

Meance i want both the line.

Please suggest some solution.

grep -B1 240 infile

Its not working :frowning:

i have typed

grep -b1 PRICE temp.log

also tried

grep -B1 "PRICE" temp.log

it gives me following error...

grep: illegal option -- 1
Usage: grep -hblcnsviw pattern file . . .

Not all grep versions have the -B option. Try with awk or sed instead.

sed -n '/240/{x;p;x;p;b;};h' file

If that doesn't work for you either, search the forums for "context grep".

awk '{
if($0 !~/^240/) 
t=$0
if($0 ~/^240/)
{
	print t
	print $0
}
}' filename

Or perhaps more idiomatically

awk '/240/ { print t; print $0; next } { t = $0 }' filename

Wow...
Its working.
Thanks a lot for this.
one quick question how to save output of this awk in a variable.

variable=`command whose output you want to capture`

The quotes around the command line are grave accents / backquotes (ASCII 96), not regular single apostrophes. Some shells offer the more readable syntax $(command whose output you want to capture)