Find a string using grep & print the line above or below that.

Hi All,

Please tell me how can I Find a string using grep & print the line above or below that in solaris?

Please share as I am unable to use grep -A or grep -B as it is not working on Solaris.

in solaris you have to use nawk. please state your input and desired output.

You could read the lines into an array:

$> cat infile
eins
zwei
drei
vier
fuenf
sechs
sieben
$> awk '{arr[NR]=$0; if($0 ~ /fuenf/)s=NR} END{print arr[s-2]}' infile
drei

In the above example the pattern to start at is fuenf and the offset is in -2.

Remind gc_sw note to use nawk (maybe).

nawk '{if (/pattern/) {print a; getline ;print } else {a=$0}}' inputfile

See Print the above and below lines for the grep pattern., use nawk of /usr/xpg4/bin/awk if on Solaris.

I am on Solaris.
& I want this:
Files contains:

abc
123
def
456
def

Now, I grep def & I want all lines which are immediate above def.
Similar is that with immediate below. I have done this once with just one command but unfortunately I have forgotten.
Please check & share any command.

awk '{A[NR]=$0}/def/{print A[NR-1]}' infile

Are there no commands in this thread and the one that I linked to that do what you require? Do you prehaps need to not print the line itself:
one above:

sed -n '/def/{g;p;};h' file

one below:

sed -n '/def/{n;p;}' file

awk:

awk '/def/&&getline' file
awk '/def/&&p{print p}{p=$0}' file

@Scruti
awk '/def/&&p{print p}{p=$0}' file if def appears at the first line of the input file, wouldn't your code add an empty line ?

i just have a doubt about what &&p condition will return ( true or false )

On the first line the variable p is no set, so {print p} will not get run (/def/&&p becomes false)

@Zaib

As Scrutinizer says - it would be very polite of you to tell us if and what does not work so far from the posted solutions instead of just posting your request again.
This should be a dialogue, no monologue.