Serious Shell Programming
  • Introduction
  • Acknowledgements
  • Basics
    • Strings
      • Single-Quotes
      • Double-Quotes
      • Unquoted Strings
      • Compound Strings
    • Here Documents
      • Here Doc
      • Indented Here Doc
      • Literal Here Doc
      • In-Memory Here Doc
    • Conditionals
      • Built-in test
      • Parameter Conditionals
      • Parameter test
    • Regex
      • grep
      • awk
      • pcre
    • Control Flow
      • Binary Operators
      • if-elif-else
      • case Statement
      • for Loop
      • while Loop
      • Functions
  • shellcheck
    • Introduction
    • Bad Advice
  • Style
    • awk
    • case
    • Redirection
    • Comments
    • trap
  • String Functions
    • substr
    • sprintf
    • replace
    • replaceall
    • replacestart
    • replaceend
    • fnmatch
  • awk
    • Pre-declaring Arrays
    • Sorting Arrays
  • Know Your limits
    • Arguments
    • Environment Variables
    • Solutions
Powered by GitBook
On this page

Was this helpful?

  1. Basics
  2. Regex

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.

PreviousRegexNextawk

Last updated 5 years ago

Was this helpful?