grep

A favorite amongst shell programmers, it can be a convenient tool. It is both portable and fast, and a number of command-line options make it a powerful ally.

For portability, avoid using egrep and/or grep -E. This chart can help you find a portable syntax to replace extended syntax.

Element

Extended syntax

Portable syntax

Grouping

( and )

\( and \)

Quantity 1 or more

+ or {1,}

\+ or \{1,\}

Quantity 0 or 1

? or {0,1}

\? or \{0,1\}

Quantity N

{N}

\{N\}

Quantity N or less

{,N}

\{,N\}

OR

\∣

Word Bounding

\< and \> (same)

\< and \> (same)

From the GNU grep(1) manual, an example of an extended regular expression would be:

egrep '19|20|25' calendar

The portable syntax would be:

grep '19\|20\|25' calendar

You can search for more than one regular expression using the -e pattern option of grep. For example:

1 #!/bin/sh
2 printf 'a\nb\n' | grep -e a -e b

Produces:

a
b

This allows you to quickly search for one or more regular expressions. A match on any given regular expression will cause the line to be printed.

Last updated