Search Text with `grep` and Regular Expressions on Linux
grep can search for literal text or regular-expression patterns. With extended regular expressions, it becomes a compact tool for locating structured values, alternatives, prefixes, suffixes, and other text patterns.
Extended Regular Expressions
Use -E:
grep -E 'regex_pattern' fileSingle quotes are often convenient in the shell because they prevent accidental expansion of regex metacharacters by the shell itself.
Match a Date-Like Pattern
grep -E '[0-9]{4}-[0-9]{2}-[0-9]{2}' log.txtThis matches text shaped like YYYY-MM-DD; it does not validate whether the date is a real calendar date.
Match Alternatives
grep -E 'error|warning' /var/log/syslogFor case-insensitive matching:
grep -Ei 'error|warning' application.logMatch the Start or End of a Line
grep -E '^ERROR' log.txt
grep -E 'success$' log.txt^ anchors the pattern to the beginning of a line and $ to the end.
Character Classes and Repetition
grep -E 'file_[[:alnum:]_-]+\.txt' list.txtPOSIX character classes such as [[:digit:]], [[:alpha:]], and [[:alnum:]] can be more portable and expressive than ASCII-only ranges in some contexts.
Show Line Numbers and Search Recursively
grep -nE 'pattern' file.txt
grep -rEn 'pattern' /path/to/directoryUse -I when recursively searching source trees and you want to skip binary files:
grep -rInE 'TODO|FIXME' src/Literal Search Instead of Regex
If the input should be treated as fixed text, use -F:
grep -F 'price[0]' file.txtThis prevents regex metacharacters from changing the meaning of the search string.
Conclusion
Use grep -E for regular expressions and grep -F for literal strings. Combine options such as -i, -n, and -r to control case sensitivity, line numbers, and recursive traversal.