Basic Matching & Case
At its simplest, grep takes a pattern and a file, and returns any line containing that pattern.
grep "error" /var/log/syslog
1. Literal Substring Matching
By default, grep performs a substring match. If you search for "cat", it will match:
catconcatenatecategorytomcat
Because of this, you must be precise with your search terms to avoid false positives.
Quoting Your Pattern
While grep error file.txt works without quotes, it is a critical best practice to always wrap your pattern in quotes (either single ' or double ").
If your pattern contains spaces, quotes are mandatory. If you do not quote it, the shell will treat the second word as the filename.
# WRONG: Searches for the word "Connection" inside a file named "refused"
grep Connection refused /var/log/syslog
# CORRECT: Searches for the phrase "Connection refused"
grep "Connection refused" /var/log/syslog
2. Case Insensitivity (-i)
By default, grep is strictly case-sensitive. Searching for error will NOT match ERROR or Error.
In log analysis, where developers might capitalize log levels inconsistently, this leads to missed data. Use the -i (--ignore-case) flag to make the search case-insensitive.
# Matches error, ERROR, Error, eRrOr, etc.
grep -i "error" /var/log/application.log
3. Fixed Strings / Disabling Regex (-F)
As the name implies, grep uses Regular Expressions. This means characters like ., *, [, and $ have special programmatic meanings.
If you are searching for a literal IP address like 192.168.1.5, the dot . actually means "match any single character" in regex. While it will match 192.168.1.5, it will also falsely match 192-168x1x5.
To force grep to treat the pattern as a plain, literal string with no special regex characters, use the -F (--fixed-strings) flag. (Historically, this was the separate fgrep command).
# Safe: Treats dots as literal dots, not regex wildcards
grep -F "192.168.1.5" /var/log/auth.log
The Performance Benefit of -F
Because -F bypasses the entire regex evaluation engine, it is significantly faster. If you are searching a 50GB file for a literal UUID, always use grep -F.