Regular expressions provide powerful methods for searching and parsing text. In Linux, they’re used extensively in commands like grep, find, locate, less, and editors like vim. This guide focuses on POSIX-compliant regex syntax: Basic (BRE) and Extended (ERE).
Regexes define symbolic patterns for matching text. While similar to shell wildcards, they offer more precision and versatility across programming and shell tools.
grep searches lines that match a given regex:
grep -h bzip dirlist*.txt| Option | Description |
|---|---|
| -i | Ignore case |
| -v | Invert match |
| -c | Count matches |
| -l / -L | Show matching / non-matching file names |
| -n | Show line numbers |
| -h | Suppress filename in output |
Metacharacters include ^ $ . [ ] { } * + ? ( ) |. Quote expressions to avoid shell interference:
grep -h '.zip' dirlist*.txt.: Matches any character^: Start of line$: End of linegrep '[bg]zip' dirlist*.txtgrep '[^bg]zip' dirlist*.txt| Class | Matches |
|---|---|
| [:alnum:] | Letters and digits |
| [:digit:] | Digits only |
| [:lower:], [:upper:] | Lower / Uppercase letters |
| [:space:] | Whitespace |
Ensure consistent behavior by exporting ASCII locale:
export LANG=POSIX( ) { }|, quantifiers, groupsgrep -E 'AAA|BBB|CCC' file.txt| Syntax | Meaning |
|---|---|
| ? | Zero or one |
| * | Zero or more |
| + | One or more |
| {n} | Exactly n |
| {n,m} | Between n and m |
| {n,} | At least n |
grep -Ev '^\([0-9]{3}\) [0-9]{3}-[0-9]{4}$' phonelist.txtfind . -regex '.*[^-_./0-9a-zA-Z].*'locate --regex 'bin/(bz|gz|zip)'less phonelist.txt
/^\([0-9]{3}\) [0-9]{3}-[0-9]{4}$/[0-9]\{3}\) [0-9]\{3\}-[0-9]\{4\}Enable highlighting with :set hlsearch
cd /usr/share/man/man1
zgrep -El 'regex|regular expression' *.gzRegex enables powerful text matching across Linux tools. By mastering grep, find, locate, and text editors, users can filter, validate, and manipulate data with precision. Understanding POSIX BRE and ERE unlocks efficient workflows in scripting, log analysis, and system administration.