# Search text files using regular expressions

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

Source: https://aminbytes.dev/bytes/gnu-and-unix-commands/regular-expressions/


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](../file-management/#wildcards-file-globbing). 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:

```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**:

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

```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:

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

```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:

| 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:

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

 (Side note: 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.

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

```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
```

| 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:

```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:

| 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` |

```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

| 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:

```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` 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: `-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

1. Which `grep` command prints only the empty lines of a file?
   - `grep '' file`
   - **`grep '^$' file`** (correct)
   - `grep '$^' file`
   `^` anchors to the start of the line and `$` to the end. With nothing in between, only empty lines match. `grep ''` matches every line.

2. Which command is the modern equivalent of `egrep 'ERROR|WARN' app.log`?
   - `grep -F 'ERROR|WARN' app.log`
   - **`grep -E 'ERROR|WARN' app.log`** (correct)
   - `grep -e 'ERROR|WARN' app.log`
   `egrep` is `grep -E` (extended regular expressions, where `|` means OR). `fgrep` is `grep -F`, which treats the pattern as plain text. `-e` just marks the next argument as a pattern.

3. A line reads `cat cat cat`. What does `sed 's/cat/dog/'` turn it into?
   - `dog dog dog`
   - **`dog cat cat`** (correct)
   - `cat cat dog`
   Without the `g` flag, `s` only replaces the first match on each line. `s/cat/dog/g` would replace all three.


