~2 min read • Updated Jul 16, 2025

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).


What Are Regular Expressions?


Regexes define symbolic patterns for matching text. While similar to shell wildcards, they offer more precision and versatility across programming and shell tools.


grep: The Regex Workhorse


grep searches lines that match a given regex:


grep -h bzip dirlist*.txt

OptionDescription
-iIgnore case
-vInvert match
-cCount matches
-l / -LShow matching / non-matching file names
-nShow line numbers
-hSuppress filename in output

Metacharacters and Anchors


Metacharacters include ^ $ . [ ] { } * + ? ( ) |. Quote expressions to avoid shell interference:


grep -h '.zip' dirlist*.txt

  • .: Matches any character
  • ^: Start of line
  • $: End of line

Bracket Expressions and Character Classes


grep '[bg]zip' dirlist*.txt

grep '[^bg]zip' dirlist*.txt

ClassMatches
[:alnum:]Letters and digits
[:digit:]Digits only
[:lower:], [:upper:]Lower / Uppercase letters
[:space:]Whitespace

Ensure consistent behavior by exporting ASCII locale:


export LANG=POSIX

BRE vs ERE


  • BRE: Requires escaping of ( ) { }
  • ERE: Supports alternation |, quantifiers, groups

grep -E 'AAA|BBB|CCC' file.txt

Quantifiers


SyntaxMeaning
?Zero or one
*Zero or more
+One or more
{n}Exactly n
{n,m}Between n and m
{n,}At least n

Practical Examples


Validate Phone Numbers


grep -Ev '^\([0-9]{3}\) [0-9]{3}-[0-9]{4}$' phonelist.txt

Find Ugly Filenames


find . -regex '.*[^-_./0-9a-zA-Z].*'

Regex Search with locate


locate --regex 'bin/(bz|gz|zip)'

Regex Search in less


less phonelist.txt
/^\([0-9]{3}\) [0-9]{3}-[0-9]{4}$

Regex in vim


/[0-9]\{3}\) [0-9]\{3\}-[0-9]\{4\}

Enable highlighting with :set hlsearch


Find Regex-Supporting Tools


cd /usr/share/man/man1
zgrep -El 'regex|regular expression' *.gz

Conclusion


Regex 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.


Written & researched by Dr. Shahin Siami