Bash Grep Extended Patterns
Extended grep patterns are search patterns that match whole families of text instead of one fixed string. The -E option turns on this extended form, so one pattern can cover spelling variants, counts, and number ranges.
Alternation matches either word
The pattern error|warning matches lines holding either word. The info line matches neither word, so it stays hidden.
printf 'error: disk full\nwarning: low space\ninfo: backup done\nerror: read failed\n' > log.txt
grep -E 'error|warning' log.txtQuantifiers control how many repeats match
The ? lets the u appear zero or one time, so color and colour match but colr does not. The + needs at least one b, and the braces allow two or three a letters only.
printf 'color\ncolour\ncolr\n' > words.txt
printf 'ac\nabc\nabbc\n' > plus.txt
printf 'a\naa\naaa\naaaa\n' > counts.txt
grep -E 'colou?r' words.txt
grep -E 'ab+c' plus.txt
grep -E '^a{2,3}$' counts.txtCharacter classes pick one character from a set
The class [A-Z] takes one capital letter, and [0-9]+ takes one or more digits. The second pattern takes a small letter instead, so it finds the other two lines.
printf 'item A12\nitem b34\nitem C56\nitem d78\n' > items.txt
grep -E '[A-Z][0-9]+' items.txt
grep -E '^item [a-z][0-9]+' items.txtCount, extract, and show context
The -c count says two lines hold error. The -o run prints only the matched words disk and read. The context run prints the warning line with one line on each side.
printf 'error: disk full\nwarning: low space\nerror: read failed\ninfo: backup done\n' > log.txt
grep -c 'error' log.txt
grep -E -o 'disk|read' log.txt
grep -B1 -A1 'warning' log.txtExample
printf 'status ok\nerror ERR-101 disk full\nstatus ok\nerror ERR-202 read failed\nwarning low space\n' > server.txt
grep -c 'error' server.txt
grep -E -o 'ERR-[0-9]+' server.txt
grep -A1 'ERR-202' server.txtKey points
- -E: turns on extended patterns for grep.
- Alternation: the | symbol tries each choice in turn.
- Quantifiers: + means one or more, ? means zero or one, and {n,m} means between n and m repeats.
- Character class: [...] matches one character from the set inside.
- -o: prints only the matching part of each line.
- -c: prints a count of matching lines, not the lines.
- Context: -A shows lines after a match, and -B shows lines before it.
In this example, the script first creates a small server log. The -c run counts the error lines and prints 2. The -o run prints only the error codes, one per line. The -A1 run prints the ERR-202 line plus the warning line after it.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which grep -E pattern matches color and colour but not colr?