Menu
Search text files using regular expressions
“Basic and extended regular expressions with grep, egrep, fgrep, sed and find: anchors, classes, quantifiers, groups and substitutions.”
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 glob | Regular expression | |
|---|---|---|
| Any one character | ? | . |
| Any number of characters | * | .* |
* on its own means | “anything” | “the previous item, zero or more times” |
| Used by | the shell, for file names | grep, 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:
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
EOFThe 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:
grep 'd.b' app.log2026-11-30 09:02:44 ERROR connection to db failed
2026-11-30 09:02:50 ERROR connection to db failedd.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:
| Anchor | Matches |
|---|---|
^ | Start of the line |
$ | End of the line |
\< and \> | Start and end of a word (GNU) |
\b | A word boundary, either side (GNU) |
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:
| Pattern | Matches |
|---|---|
[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:
| Quantifier | Meaning | Example (ERE) | Matches |
|---|---|---|---|
* | 0 or more | ab* | a, ab, abbb |
+ | 1 or more | ab+ | ab, abbb |
? | 0 or 1 | colou?r | color, 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.
grep -oE '[0-9]{2}%' app.log
grep -oE '[[:alnum:]._-]+@[[:alnum:].-]+\.[a-z]{2,}' app.log81%
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
\1matches the same text the first group matched.(.)\1finds a doubled character:
printf 'hello\nbook\nabc\n' | grep -E '(.)\1'hello
bookBasic 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:
| Meaning | BRE (grep, sed) | ERE (grep -E, sed -E) |
|---|---|---|
| One or more | \+ | + |
| Zero or one | \? | ? |
| Group | \( \) | ( ) |
| Repeat count | \{2,4\} | {2,4} |
. * ^ $ [ ] | special | special |
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:
grep 'ERROR\|WARN' app.log | wc -l
grep -E 'ERROR|WARN' app.log | wc -l
grep 'ERROR|WARN' app.log | wc -l3
3
0The 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:
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/'30.11.2026
30.11.2026ERE 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.
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.
| Option | Meaning |
|---|---|
-i | Ignore case |
-v | Invert: print lines that don’t match |
-c | Count matching lines |
-n | Show line numbers |
-l / -L | Only list file names that match / don’t match |
-r / -R | Search directories recursively (-R also follows symlinks) |
-w | Match whole words only |
-x | Match whole lines only |
-o | Print only the matching part |
-E | Extended regex (ERE) |
-F | Fixed string: no regex at all |
-e PATTERN | Add a pattern (use several for OR) |
-A n / -B n / -C n | Show n lines after / before / around each match |
-h / -H | Hide / show the file name in front of each match |
-q | Quiet: print nothing, only set the exit status |
grep -i info app.log
grep -c ERROR app.log
grep -n WARN app.log
grep -A1 WARN app.log2026-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 failedgrep -w cat finds “the cat sat” but not “catalog”. grep -q is made for scripts:
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:
egrepis the same asgrep -E(extended regex).fgrepis the same asgrep -F(fixed strings, no regex). It’s useful when the text is full of special characters, like an IP address or$var.
echo "price: 1.50 or 1x50" | grep -o '1.50'
echo "price: 1.50 or 1x50" | grep -oF '1.50'1.50
1x50
1.50As 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:
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/etc/ssh/sshd_config:#PermitRootLogin prohibit-passwordTo 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 .*/:
find . -regex '.*/IMG_[0-9]*\.jpg'
find . -regextype posix-extended -iregex '.*/img_[0-9]+\.jpe?g'./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:
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 matchb-a-a
b-b-b
a-b-a| Flag | Meaning |
|---|---|
g | Replace every match on the line |
2 (a number) | Replace only that occurrence |
i or I | Ignore case (GNU) |
p | Print the line if a replacement was made (with -n) |
In the replacement, & stands for the whole match and \1 to \9 for the groups:
echo "port 8080" | sed 's/[0-9][0-9]*/[&]/'port [8080]The / is only a convention. Any character after s becomes the delimiter, which saves a lot of escaping with paths:
echo "/usr/local/bin" | sed 's|/usr/local|/opt|'/opt/binAddresses: which lines#
Put an address before a command to limit it to certain lines:
| Address | Lines |
|---|---|
3 | Line 3 |
2,5 | Lines 2 to 5 |
$ | The last line |
/regex/ | Lines that match |
/start/,/end/ | From a line matching start to one matching end |
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 linesOther commands#
| Command | Action |
|---|---|
d | Delete the line |
p | Print the line (use with -n) |
i\ text or i text | Insert a line before |
a\ text or a text | Append a line after |
c\ text or c text | Change (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:
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.bakCaution
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 option | Meaning |
|---|---|
-n | Don’t print every line automatically |
-e script | Add a command (several allowed) |
-f file | Read commands from a file |
-E or -r | Use 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:
-iignore case,-vinvert,-ccount,-nline numbers,-lfile names,-rrecursive,-wwhole word,-oonly the match,-qquiet. sed 's/old/new/'replaces the first match per line,/gall.&is the whole match,\1the first group.-nwithpprints selected lines,ddeletes.sed -iedits in place,sed -i.bakkeeps a backup.sed -E(or-r) for ERE.find -regexmatches the whole path;-iregexignores case;-regextype posix-extendedfor ERE.- Quote regexes with single quotes so the shell doesn’t expand them. The reference is
man 7 regex.
Answer these 3 questions to commit this byte to your learning path.
Reset. This byte isn't committed any more. Answer the questions again to commit it.
$ git commit -m "learn(lpic-103): Search text files using regular expressions"
[main 59b0094] learn(lpic-103): Search text files using regular expressions
1 byte changed, 3 insertions(+)
See it on your path Already committed . Try the questions again any time, it won't undo anything. To uncommit it and start over: