grepping around

Using shell scripts, I use grep to find the word �error� in a log file:
grep error this.log.
How can I print or get the line 3 lines below the line that word �error� is located?
Thanks in advance for your response.

awk 'x&&!--x;/error/{x=3}' file

Use nawk or /usr/xpg4/bin/awk on Solaris.

With sed:

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

With shell:

while read;do case $REPLY in *error*)read;read;read;echo "$REPLY";;esac;done<file

hey please try the following one

grep -A <<n>> <<search pattern>> file_name
grep -B <<n>> <<search pattern>> file_name

NOTE: n is the number of lines you want to traverse before/after the search pattern .

radoulov,
You are very knowledgeable.
nawk 'x&&!--x;/error/{x=3}' file
is what I needed.:slight_smile:
Thank you.

Hi. I am a new user to this site. This is actually my first post.

My question is similar. How can I grep for a particular string and have grep return that string along with the next 10 lines beneath the grepped string? manas_ranjan said to issue grep -A <<n>> <<search pattern>> file_name, but it doesn't look like -A is a grep option on the Solaris 10 box I am trying to run the command on. :eek: I assume I should install the latest version of GNU grep, but I am not an admin of this box, so that is not an option.

Are there alternatives such as awk/nawk or sed? If so, what would the exact commands be?

Thanks you very much in advance. :slight_smile:

  • LaLonde
awk 'c&&c--;/pattern/{c=10;print}' file

Use nawk or /usr/xpg4/bin/awk on Solaris.

refer to radoulov's post he has given the example.

heres another alternative

 sed -n '/1/{n;p;n;p;n;p;n;p;n;p;n;p;n;p;n;p;n;p;n;p;}' test

Hey guys, thanks for the quick responses!

try this $cat <logfile>|grep error|tail -3

You can use this also--

lineno=`grep -n error test8 | cut -d" " -f1 | cut -d":" -f1`
sed -n `expr $no + 1`,`expr $no + 3`p test8

Thanks
Namish