grep replacement

anw at nott-cs.UUCP anw at nott-cs.UUCP
Thu Jun 2 02:17:27 AEST 1988


In article <6866 at elroy.Jpl.Nasa.Gov> alan at cogswell.Jpl.Nasa.Gov (Alan S. Mazer)
writes:
> One thing I would _love_ is to be able to find the context of what I've
> found, for example, to find the two (n?) surrounding lines.  I have wanted
> to do this many times and there is no good way.

	See below.  Does n == 4, but easily changed.

In article <590 at root44.co.uk> gwc at root.co.uk (Geoff Clare) writes:
>
> Most of the useful things people have been saying they would like to be
> able to do with 'grep' can already be done very simply with 'sed'.

	Which is not to say that they shouldn't also be in "*grep"!

>	[ good examples omitted ]
>
> It should also be possible to get a small number of context lines by
> judicious use of the 'hold space' commands (g, G, h, H, x), but I haven't
> tried it.  [ ... ]

	The following is "/usr/bin/kwic" on this machine (PDP 11/44 running
V7).  I wrote it about three years ago in response to a challenge from some
AWK zealots;  it runs *much* faster than the equivalent AWK script.  That
is, it is sloooww rather than ssllloooooowwww.  I have a manual entry for
it which is too trivial to send.  Bourne shell, of course.  Use at whim
and discretion.  Several minor bugs, mainly (I hope!) limitations of or
between "sh" and "sed".  (Note that the various occurrences of multiple
spaces in "s..." commands are all TABs, in case mailers/editors/typists
have mangled things.)

> By the way, does anyone know why the ';' command terminator in 'sed' is
> not documented?  It works on all the systems I've tried it on, but I
> have never found it in any manuals.  It's so much nicer than putting
> the commands on separate lines, or using multiple '-e' options.

	No, I don't know why, but it isn't the only example in Unix of a
facility most easily discovered by looking in the source.  I've occasionally
used it, but I tried re-writing the following that way, and it *didn't* look
so much nicer;  in fact it looked 'orrible.

--------------------------------- [cut here] -----------------------------
[ $# -eq 0 ] && { echo "Usage: $0 pattern [file] ..." 1>&2; exit 1; }

l='[^\n]*\n' pat="$1" shift

exec sed -n   "/$pat"'/ b found
			s/^/	/
			H
			g
      /^'"$l$l$l$l$l"'/ s/\n[^\n]*//
			h
			b
	: found
			s/^/++	/
			H
			g
			s/.//p
			s/.*//
			h
	: loop
		      $ b out
			n
	     /'"$pat"'/ b found
			s/^/	/
			H
			g
	/^'"$l$l$l$l"'/ !b loop
	: out
			s/.//p
			s/.*/-----------------/
			h
	    ' ${1+"$@"}

-- 
Andy Walker, Maths Dept., Nott'm Univ., UK.
anw at maths.nott.ac.uk



More information about the Comp.unix.questions mailing list