Regular expressions in Linux: basics for grep and sed
Updated November 1, 2026
A regular expression is a pattern that describes a set of text strings.
Common cases
. # any single character
^start # anchor to the start of the line
end$ # anchor to the end of the line
[0-9]+ # one or more digits (grep -E)
error|fail # match one or the other (grep -E)Sample output
$ grep 'ERROR|WARN' app.log
$ echo $?
1
$ grep -E 'ERROR|WARN' app.log
2026-07-19 09:15:02 WARN slow query 1.4s on table orders
2026-07-19 09:16:10 ERROR connection refused to redis:6379
...
$ grep -oE '[0-9]+ms' app.log
14ms
31ms
88msHow it works: basic versus extended
Regular expressions have two dialects in the GNU tools: basic (BRE) and extended (ERE). In basic, the characters
+,?,|and()are literal, and to give them special meaning you escape them:\+. Thegrep -Eflag (andsed -E) turns on the extended dialect, where they work directly:error|fail,[0-9]+. Mind greediness:.*grabs as much as it can. And do not confuse a regular expression with shell globbing:*in the shell and*in a regex mean different things.
Common mistakes
A dot in a pattern means any character, not a dot. grep 'app.log' names.txt also matches the line appXlog. When you mean a literal dot, escape it: app\.log. When you want no pattern magic at all, search literally: grep -F 'app.log'.
^ means two different things. At the start of a pattern it anchors to the start of the line: grep '^v' takes lines that begin with v. Right after the opening bracket of a class it negates: [^0-9] is any character except a digit, and grep '[^0-9]' finds every line that holds at least one non-digit.
The pattern 'listen 80$' can miss a line that looks right on screen. A file from Windows carries a carriage return before the newline, so $ sits after that character and not after 80. cat -A shows the truth: listen 80^M$. The fix is a substitution: sed -i 's/\r$//' file.
Used in
You need this in the lesson Text: grep, sed, awk. The theory is the chapter Bash in depth.
See also
The grep command, The sed command, The awk command.
Try it
Open the sandbox: a real throwaway Linux terminal in your browser. Run the commands above by hand - the container is deleted when you leave.