Menu

GNU and Unix Commands

Step 7 of 8 LPIC-1 103.7weight 3

Search text files using regular expressions

“Basic and extended regular expressions with grep, egrep, fgrep, sed and find: anchors, classes, quantifiers, groups and substitutions.”

View .md

Sooner or later you need to find something in a pile of text: every failed login in a log, every config line that isn’t a comment, every email address in a dump. Searching for a fixed word isn’t enough when the thing you want varies. A regular expression (regex) is a pattern that describes text: “a line that starts with a date”, “three digits, a dash, four digits”, “either ERROR or WARN”.

Regexes work in many tools. For LPIC-1 the important ones are grep to search and sed to change text, plus find to match file paths.

Regex vs wildcards#

Don’t confuse regular expressions with the shell’s wildcards. They look alike but mean different things:

Shell globRegular expression
Any one character?.
Any number of characters*.*
* on its own means“anything”“the previous item, zero or more times”
Used bythe shell, for file namesgrep, sed, find -regex, … for text

Because the shell would expand * and ? itself, always put regexes in single quotes: grep 'a.*b' file.

A sample log#

Make this file to follow along:

bash
cat > app.log <<'EOF'
2026-11-30 08:15:02 INFO  server started on port 8080
2026-11-30 08:15:09 WARN  disk usage at 81%
2026-11-30 09:02:44 ERROR connection to db failed
2026-11-30 09:02:45 info  retrying in 5s
2026-11-30 09:02:50 ERROR connection to db failed
2026-11-30 10:11:00 INFO  user amin@example.com logged in
EOF

The building blocks#

Literal text and the dot#

Most characters just match themselves: grep ERROR app.log finds lines containing “ERROR”. The dot . matches any single character:

bash
grep 'd.b' app.log
text
2026-11-30 09:02:44 ERROR connection to db failed
2026-11-30 09:02:50 ERROR connection to db failed

d.b matched d b in “to db”. To match a real dot, escape it with a backslash: '1\.50'.

Anchors#

Anchors don’t match characters, they match positions:

AnchorMatches
^Start of the line
$End of the line
\< and \>Start and end of a word (GNU)
\bA word boundary, either side (GNU)
bash
grep '^root' /etc/passwd     # lines that start with root
grep 'bash$' /etc/passwd     # lines that end with bash
grep -v '^#' /etc/ssh/sshd_config | grep -v '^$'   # config without comments and empty lines

^$ is an empty line: start, then immediately the end.

Bracket expressions#

Square brackets match one character from a set:

PatternMatches
[abc]a, b or c
[a-z], [0-9]One character from the range
[^abc]One character that is not a, b or c
[[:digit:]]A digit (same as [0-9])
[[:alpha:]], [[:alnum:]]A letter; a letter or digit
[[:upper:]], [[:lower:]]Upper or lower case letter
[[:space:]]Space, tab and other whitespace
[[:punct:]]Punctuation

Note that ^ means “not” only as the first character inside brackets. Outside, it’s the start-of-line anchor. And the POSIX classes need their own brackets: [[:digit:]], not [:digit:].

Quantifiers#

A quantifier says how many times the item before it may repeat:

QuantifierMeaningExample (ERE)Matches
*0 or moreab*a, ab, abbb
+1 or moreab+ab, abbb
?0 or 1colou?rcolor, colour
{3}Exactly 3[0-9]{3}123
{2,}2 or more(ab){2,}abab, ababab
{2,4}2 to 4[0-9]{2,4}12, 1234

.* means “anything at all, or nothing”, and it’s greedy: it matches as much as it can.

bash
grep -oE '[0-9]{2}%' app.log
grep -oE '[[:alnum:]._-]+@[[:alnum:].-]+\.[a-z]{2,}' app.log
text
81%
amin@example.com

-o prints only the matching part instead of the whole line, which is great for checking what your regex really matches.

Alternation, groups and backreferences#

  • | means OR: ERROR|WARN.
  • Parentheses ( ) group items, so a quantifier or | applies to the whole group: (ab)+, (cat|dog)s.
  • A backreference \1 matches the same text the first group matched. (.)\1 finds a doubled character:
bash
printf 'hello\nbook\nabc\n' | grep -E '(.)\1'
text
hello
book

Basic vs extended regular expressions#

There are two flavors. Basic regular expressions (BRE) are the default for grep and sed. Extended regular expressions (ERE) are used with grep -E and sed -E. The difference is mostly which characters are special without a backslash:

MeaningBRE (grep, sed)ERE (grep -E, sed -E)
One or more\++
Zero or one\??
Group\( \)( )
Repeat count\{2,4\}{2,4}
. * ^ $ [ ]specialspecial

OR works the same way: in BRE you put a backslash before the pipe (ERROR\|WARN), in ERE you use a plain pipe (ERROR|WARN). See the difference:

bash
grep 'ERROR\|WARN' app.log | wc -l
grep -E 'ERROR|WARN' app.log | wc -l
grep 'ERROR|WARN' app.log | wc -l
text
3
3
0

The last one searched for the literal text ERROR|WARN, because in BRE a plain | is just a character. Same story for the date swap below, written both ways:

bash
echo "2026-11-30" | sed 's/\([0-9]\{4\}\)-\([0-9]\{2\}\)-\([0-9]\{2\}\)/\3.\2.\1/'
echo "2026-11-30" | sed -E 's/([0-9]{4})-([0-9]{2})-([0-9]{2})/\3.\2.\1/'
text
30.11.2026
30.11.2026

ERE is easier to read whenever you use groups or +. \+, \? and \| in BRE are GNU extensions; strict POSIX BRE doesn’t have them.

The full reference is the manual page regex(7): man 7 regex. It describes both flavors as POSIX defines them.

GNU grep also has -P for Perl-compatible regexes, with shortcuts like \d for a digit. It’s handy, but it’s not part of the LPIC objective, and BRE/ERE are what the exam asks about.

grep: search for lines#

grep prints every line that matches a pattern. It reads files or standard input.

OptionMeaning
-iIgnore case
-vInvert: print lines that don’t match
-cCount matching lines
-nShow line numbers
-l / -LOnly list file names that match / don’t match
-r / -RSearch directories recursively (-R also follows symlinks)
-wMatch whole words only
-xMatch whole lines only
-oPrint only the matching part
-EExtended regex (ERE)
-FFixed string: no regex at all
-e PATTERNAdd a pattern (use several for OR)
-A n / -B n / -C nShow n lines after / before / around each match
-h / -HHide / show the file name in front of each match
-qQuiet: print nothing, only set the exit status
bash
grep -i info app.log
grep -c ERROR app.log
grep -n WARN app.log
grep -A1 WARN app.log
text
2026-11-30 08:15:02 INFO  server started on port 8080
2026-11-30 09:02:45 info  retrying in 5s
2026-11-30 10:11:00 INFO  user amin@example.com logged in
2
2:2026-11-30 08:15:09 WARN  disk usage at 81%
2026-11-30 08:15:09 WARN  disk usage at 81%
2026-11-30 09:02:44 ERROR connection to db failed

grep -w cat finds “the cat sat” but not “catalog”. grep -q is made for scripts:

bash
grep -q ERROR app.log && echo "found errors"

grep exits with 0 if something matched, 1 if nothing matched and 2 on an error (like a missing file).

egrep and fgrep#

Two old names you’ll still see:

  • egrep is the same as grep -E (extended regex).
  • fgrep is the same as grep -F (fixed strings, no regex). It’s useful when the text is full of special characters, like an IP address or $var.
bash
echo "price: 1.50 or 1x50" | grep -o '1.50'
echo "price: 1.50 or 1x50" | grep -oF '1.50'
text
1.50
1x50
1.50

As a regex, the . in 1.50 matched the x too. With -F it’s just a dot.

Both commands are deprecated. Recent GNU grep versions may print a warning that egrep is obsolescent. Use grep -E and grep -F in new scripts, but recognize the old names on the exam.

Searching the filesystem#

Regexes can search inside many files at once, or match file names.

To search the contents of a whole tree, use grep -r:

bash
grep -r 'PermitRootLogin' /etc/ssh
grep -rl '^Port' /etc/ssh               # only the file names
grep -rn --include='*.conf' 'Listen' /etc   # only in .conf files, with line numbers
text
/etc/ssh/sshd_config:#PermitRootLogin prohibit-password

To find files whose path matches a regex, use find -regex. The regex must match the whole path, including the ./ at the start, which is why most patterns begin with .*/:

bash
find . -regex '.*/IMG_[0-9]*\.jpg'
find . -regextype posix-extended -iregex '.*/img_[0-9]+\.jpe?g'
text
./IMG_001.jpg
./IMG_001.jpg
./img_002.JPG

-iregex ignores case. find uses Emacs-style regexes by default; -regextype posix-extended switches to the ERE you know from grep -E. The locate command also accepts a regex with -r.

sed: change text with regexes#

sed (stream editor) reads text line by line, applies commands to it and prints the result. The original file is left alone unless you use -i.

Substitute: s#

The command you’ll use most is s/regex/replacement/flags:

bash
echo "a-a-a" | sed 's/a/b/'     # first match on each line
echo "a-a-a" | sed 's/a/b/g'    # g: all matches
echo "a-a-a" | sed 's/a/b/2'    # only the 2nd match
text
b-a-a
b-b-b
a-b-a
FlagMeaning
gReplace every match on the line
2 (a number)Replace only that occurrence
i or IIgnore case (GNU)
pPrint the line if a replacement was made (with -n)

In the replacement, & stands for the whole match and \1 to \9 for the groups:

bash
echo "port 8080" | sed 's/[0-9][0-9]*/[&]/'
text
port [8080]

The / is only a convention. Any character after s becomes the delimiter, which saves a lot of escaping with paths:

bash
echo "/usr/local/bin" | sed 's|/usr/local|/opt|'
text
/opt/bin

Addresses: which lines#

Put an address before a command to limit it to certain lines:

AddressLines
3Line 3
2,5Lines 2 to 5
$The last line
/regex/Lines that match
/start/,/end/From a line matching start to one matching end
bash
sed -n '/ERROR/p' app.log          # like grep: -n stops the default printing, p prints
sed '/^#/d;/^$/d' /etc/host.conf   # delete comments and empty lines
sed '1d' data.csv                  # drop the header line
sed '3,$d' app.log                 # keep only lines 1 and 2
sed '/WARN/s/disk/DISK/' app.log   # substitute only on WARN lines

Other commands#

CommandAction
dDelete the line
pPrint the line (use with -n)
i\ text or i textInsert a line before
a\ text or a textAppend a line after
c\ text or c textChange (replace) the whole line
y/abc/xyz/Translate characters, like tr

Run several commands with ; or several -e options: sed -e 's/ERROR/E/' -e 's/WARN/W/'.

Editing files in place#

-i writes the result back to the file. Give it a suffix to keep a backup:

bash
sed -i 's/^#Port 22/Port 2222/' /etc/ssh/sshd_config
sed -i.bak 's/WARN/warn/' app.log      # keeps the original as app.log.bak

Caution

sed -i changes the file with no undo. Run the command without -i first and check the output, or always use -i.bak on config files.

sed optionMeaning
-nDon’t print every line automatically
-e scriptAdd a command (several allowed)
-f fileRead commands from a file
-E or -rUse extended regex (ERE)
-i[SUFFIX]Edit files in place, optional backup suffix

Exam checklist#

  • . any one character, * zero or more of the previous item, ^ start of line, $ end of line, [abc] one of, [^abc] none of, [[:digit:]] a class.
  • ERE adds +, ?, |, ( ) and {n,m} without backslashes. In GNU BRE you write \+, \?, \|, \( \), \{n,m\}.
  • grep -E = egrep (extended), grep -F = fgrep (fixed string, no regex). Both old names are deprecated.
  • grep options: -i ignore case, -v invert, -c count, -n line numbers, -l file names, -r recursive, -w whole word, -o only the match, -q quiet.
  • sed 's/old/new/' replaces the first match per line, /g all. & is the whole match, \1 the first group. -n with p prints selected lines, d deletes.
  • sed -i edits in place, sed -i.bak keeps a backup. sed -E (or -r) for ERE.
  • find -regex matches the whole path; -iregex ignores case; -regextype posix-extended for ERE.
  • Quote regexes with single quotes so the shell doesn’t expand them. The reference is man 7 regex.

Byte check

0/3

Answer these 3 questions to commit this byte to your learning path.

  1. Which grep command prints only the empty lines of a file?
  2. Which command is the modern equivalent of egrep 'ERROR|WARN' app.log?
  3. A line reads cat cat cat. What does sed 's/cat/dog/' turn it into?
Search posts and bytes

Optional account

Keep your progress everywhere

Everything on AminBytes is free to read, with or without an account. Sign in only if you want your commits, streak and merged topics saved, on every device.

or

We keep only your name, avatar and which bytes you finished, and you can delete it all anytime. Privacy