How to search file contents with grep
Search inside files with grep — recursive search, case-insensitive matching, line numbers, context, regex and piping output from other commands into grep.
- Searching inside files with grep
- Search recursively
- Case-insensitive matching
- Show line numbers
- Match whole words and invert
- Count matches
- Show surrounding context
- Using regular expressions
- Piping into grep
Searching inside files with grep
While find locates files by their name or metadata, grep searches what's inside them. It scans for lines matching a pattern and prints them. The basic form is grep 'pattern' file:
grep 'database' config/app.php
Search recursively
To search every file under a directory, add -r (recursive). This is the one I use most:
grep -r 'API_KEY' .
Case-insensitive matching
By default grep is case-sensitive. Add -i to ignore case, so Error, error and ERROR all match:
grep -ri 'todo' src/
Show line numbers
Add -n to prefix each match with its line number, which makes jumping to it in an editor much faster:
grep -n 'function' app.js
Match whole words and invert
Use -w to match a whole word only, so searching log won't also match login or catalog:
grep -w 'log' app.php
Flip the logic with -v to print lines that don't match — useful for filtering noise out of a file:
grep -v '^#' config.ini
That example drops every commented line (those starting with #).
Count matches
When you only care how many times something appears, -c prints the count of matching lines instead of the lines themselves:
grep -c 'POST' access.log
Show surrounding context
Sometimes the matching line alone isn't enough. Use -A for lines after, -B for before, and -C for both:
grep -C 3 'Exception' storage/logs/laravel.log
This prints each match with 3 lines on either side.
Using regular expressions
The pattern is a regular expression, so you can match more than literal text. Add -E for extended regex syntax like alternation and +:
grep -E 'warning|error|critical' app.log
This finds any line containing one of those three words.
Piping into grep
grep really shines at the end of a pipe, filtering the output of another command. This is everyday glue on the command line:
ps aux | grep nginx
git log --oneline | grep 'fix'
Combine these flags freely — for example grep -rin 'token' . gives you a recursive, case-insensitive search with line numbers — and grep becomes one of the most useful tools in your kit. For the wider toolkit, see Linux command line basics.