Polishing the wegrep Wrapper Script

I'm being a bit lazy here by exploiting how the script works too. If it can show matching lines from a file, it also can show matching lines that have had the ANSI sequences slipped in. So here's the new flow, and it's a bit more complicated than my original stab at this script:


sed ''/$1/s//`printf "\033[32m$1\033[0m"`/'' "$2" | \
sed = | sed 'N;s/\n/:  /' | \
sed -n "${before},${after}p"

Four invocations of sed in a row—ah, I love Linux!

In the above, the first sed invocation adds the ANSI sequences, the second and third work together to add the line number prefixes, and the fourth shows the lines in the stream from the range $before to $after.

To see how those are calculated, here's the full script:


#!/bin/sh
# wegrep - grep with context and regular expressions
grep=/usr/bin/grep
sed=/usr/bin/sed
context=1
matches=0
if [ $# -ne 2 ] ; then
  echo "Usage: wegrep [pattern] filename" ; exit 1
fi
for match in $($grep -n -E "$1" "$2" | cut -d: -f1)
do
  before=$(( $match - $context ))
   after=$(( $match + $context ))
  if [ $matches -eq 0 ] ; then
    echo "-----"
  fi
  sed ''/$1/s//`printf "\033[32m$1\033[0m"`/'' "$2" | \
    sed = | sed 'N;s/\n/:       /' | \
    sed -n "${before},${after}p"
  echo "-----"
  matches=$(( $matches + 1 ))
done
exit 0

It's surprisingly short given how useful this wrapper script is and how many new features have been added to an older, crude grep program.

And, here it is in use:


$ sh wegrep.sh 'Alice' wonderland.txt
-----
12:
13:     Alice was beginning to get very tired of sitting by her
14:     sister on the bank, and of having nothing to do: once
-----
16:     reading, but it had no pictures or conversations in it,
17:     'and what is the use of a book,' thought Alice 'without
18:     pictures or conversation?'
-----
27:     There was nothing so very remarkable in that; nor did
28:     Alice think it so very much out of the way to hear the
29:     Rabbit say to itself, 'Oh dear! Oh dear! I shall be
-----

There's still a hiccup in the script, however. Because of the ANSI sequence sed invocation, the proper functionality of regular expressions is lost (try it, you'll see what I mean). Is it a huge problem? Maybe not, but I'm going to leave solving it as an exercise for you, the reader.

As always, if you have suggestions, let me know via e-mail: dave@linuxjournal.com.

______________________

Dave Taylor has been hacking shell scripts for over thirty years. Really. He's the author of the popular "Wicked Cool Shell Scripts" and can be found on Twitter as @DaveTaylor and more generally at www.DaveTaylorOnline.com.