24.07.2018 Views

Bash-Beginners-Guide

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 4. Regular expressions<br />

In this chapter we discuss:<br />

♦ Using regular expressions<br />

♦ Regular expression metacharacters<br />

♦ Finding patterns in files or output<br />

♦ Character ranges and classes in <strong>Bash</strong><br />

4.1. Regular expressions<br />

4.1.1. What are regular expressions?<br />

A regular expression is a pattern that describes a set of strings. Regular expressions are constructed<br />

analogously to arithmetic expressions by using various operators to combine smaller expressions.<br />

The fundamental building blocks are the regular expressions that match a single character. Most characters,<br />

including all letters and digits, are regular expressions that match themselves. Any metacharacter with special<br />

meaning may be quoted by preceding it with a backslash.<br />

4.1.2. Regular expression metacharacters<br />

A regular expression may be followed by one of several repetition operators (metacharacters):<br />

Table 4-1. Regular expression operators<br />

Operator Effect<br />

. Matches any single character.<br />

? The preceding item is optional and will be matched, at most, once.<br />

* The preceding item will be matched zero or more times.<br />

+ The preceding item will be matched one or more times.<br />

{N}<br />

{N,}<br />

{N,M}<br />

The preceding item is matched exactly N times.<br />

The preceding item is matched N or more times.<br />

The preceding item is matched at least N times, but not more than M times.<br />

- represents the range if it's not first or last in a list or the ending point of a range in a list.<br />

^<br />

Matches the empty string at the beginning of a line; also represents the characters not in the range<br />

of a list.<br />

$ Matches the empty string at the end of a line.<br />

\b Matches the empty string at the edge of a word.<br />

\B Matches the empty string provided it's not at the edge of a word.<br />

\< Match the empty string at the beginning of word.<br />

\> Match the empty string at the end of word.<br />

Chapter 4. Regular expressions 56

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!