SUMMARY: grep for more than single lines

From: Wilkinson, Daniel <>
Date: Mon Jun 18 2001 - 10:56:56 EDT
Thanks everyone - I shan't name you all, as I've has 20+ emails in 10
minutes already, and am aleady shamed by my pitifully woeful knowledge,
without having to name those cleverer than I...

The general opinion was to use GNU grep, but I wasn't keen on installing any
more packages etc which is why I was wandering down the script route.  If
you can, or have Gnu grep installed, then do this:

grep -A5 -B5 string file

Another way was with sed:

sed -n -e '/string/{=;x;1!p;g;$!N;p;D;}' -e h <inputfile

to print 1 line before and after, although I didn't play around with it to
do more than one line either way, because this weeks winner is Sarah
Eckhause, with:

	#  Number of lines to print
	NPRINT=`expr $BEFORE + $AFTER + 1`

	# Find line number of the string in question

	LINENO=`grep -n 'string'  FILETOSEARCH | awk -F':' '{ print $1 }' |
head -1`

	LINESTRT=`expr $LINENO - $BEFORE | sed 's/^  *//'`


Which does exactly what I want, in roundabout the way I was starting to try,
although I had temporarily forgotten about head/tail, and was trying to
trick more into doing something it'll never do...

Thanks Sarah!


-----Original Message-----
From: Wilkinson, Daniel []
Sent: 18 June 2001 14:46
To: Sun Managers Mailing List
Subject: grep for more than single lines


I need a command or script to grep for a string within a file, and then
instead of just printing out that single line, getting it to print the
previous 10 lines, or the following 5 lines, or a combination of both, such
that I can cut out an error message in context, and see what happened before
or after etc.  Am I being stupid, and does this exist as a command in
Solaris, and if not, has anyone written anything already before I start?


sunmanagers mailing list
Received on Mon Jun 18 15:56:56 2001

This archive was generated by hypermail 2.1.8 : Wed Mar 23 2016 - 16:24:57 EDT