How to Use grep Command in Linux: Syntax and Examples
The
grep command in Linux searches for specific text patterns inside files or input streams. Use grep 'pattern' filename to find lines containing the pattern in a file. It helps quickly locate text in logs, scripts, or any text data.Syntax
The basic syntax of grep is:
grep [options] 'pattern' filename
Here, pattern is the text or regular expression you want to find, and filename is the file to search in. Options modify how grep works, like ignoring case or showing line numbers.
bash
grep [options] 'pattern' filenameExample
This example searches for the word error in a file named log.txt. It prints all lines containing error.
bash
echo -e "info: start\nerror: failed to load\ninfo: done" > log.txt grep 'error' log.txt
Output
error: failed to load
Common Pitfalls
Common mistakes include:
- Not quoting the pattern, which can cause shell expansion issues.
- Forgetting that
grepis case-sensitive by default. - Using
grepwithout specifying a file or input.
Always quote your pattern and use -i to ignore case if needed.
bash
grep error log.txt # May miss 'Error' or 'ERROR' grep -i 'error' log.txt # Finds 'error', 'Error', 'ERROR'
Quick Reference
| Option | Description |
|---|---|
| -i | Ignore case distinctions |
| -n | Show line numbers with output |
| -v | Invert match, show lines NOT matching pattern |
| -r | Recursively search directories |
| -c | Count matching lines only |
Key Takeaways
Use
grep 'pattern' filename to find text in files.Quote your pattern to avoid shell issues.
Use
-i to search case-insensitively.Add
-n to see line numbers of matches.Remember
grep can search recursively with -r.