The Many Paths to a Solution

A project I'm involved with has made me think about how there are always many solution paths for any given problem in the Linux universe. For this other project, I wanted to cobble together a version of grep that let me specify proper regular expressions without having to worry about the -E flag and get a context for the matches too.

These are both popular expansions to grep, of course: the former demonstrated by both grep -E and the egrep shortcut, while the latter task is done with grep -C and, on some UNIX and Linux systems, wgrep.

But, there are a lot of different ways to create that particular functionality that don't involve relying on a modern version of grep; older versions might have the -E flag, but don't include support for contextualization.

So in this article, I thought it would be interesting to look at different ways to produce what I shall call wegrep, a version of grep that includes both the -C contextual window and the -E regular expression pattern support.

Wrapper, Maybe We Just Need a Wrapper

If you have the modern GNU grep, which you can ascertain by simply trying to use the -C flag, this all becomes easy:

$ grep -C
grep: option requires an argument -- C

There's a pretty gnarly usage statement after this, but if your version can understand the -C or its wordy sibling -context, you're in luck.

Enter a "wrapper", a simple script that changes the default behavior of a program. At its simplest, it actually can be a system alias, so this:

alias ls="/bin/ls -F"

is a sort of wrapper, ensuring that whenever I run the ls command, the -F flag is specified.


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