issue with grep -B option

hi friends,
i have a file where every word is present in a new line for example:
more file1:

i want to fetch previous line wherever i am getting "as" as a keyword.
i tried at home the follwing code in linex:

grep -B 1 "as" file1

ouput:
caste
caste1
it was working!!
but now i am working on ksh88. its not working . i am getting error as :
grep: illegal option -- B
Usage: grep -hblcnsviw pattern file . . .

that mean this option is not there in ksh88. is there any replacement for this command.

thanks in advance :slight_smile:

Hi,

Try this one,

awk '/as/{print p;}{p=$0;}' file

use nawk instead of awk if you dont have awk.
Cheers,
Ranga:-)

1 Like

Just tweaking the previous solution a bit to get the correct results:

awk '/^as$/{print p}{p=$0}' file
1 Like

its working!!. could you please explin the "p=$0" part. thanks

we are storing the previous value in p variable and using whenever required.

1 Like

thanks. one issue insted of hardcoding it, if i am storing the "as" keywornd in a file and serching it.
for example:
word="as"

awk '/^\$word$/{print p}{p=$0}' file

not getting anything :frowning: . please help

I assume that you meant "variable" instead of "file".

In that case, try

word="as"
awk "/^$word$/{print p}{p=\$0}" file
1 Like