How to Use grep in Bash: Syntax, Examples, and Tips
Use
grep in bash to search for text patterns in files or command output by typing grep 'pattern' filename. It prints lines containing the pattern, helping you quickly find information in text data.Syntax
The basic syntax of grep is:
grep 'pattern' filename: Search for pattern in the specified filename.pattern: The text or regular expression you want to find.filename: The file or files to search inside.
You can also use options like -i for case-insensitive search or -r to search recursively in directories.
bash
grep 'pattern' filename # Common options: grep -i 'pattern' filename # ignore case grep -r 'pattern' directory/ # recursive search
Example
This example shows how to search for the word apple in a file named fruits.txt. It prints all lines containing apple.
bash
echo -e "apple\nbanana\nApple pie\ncherry" > fruits.txt grep 'apple' fruits.txt
Output
apple
Common Pitfalls
Common mistakes when using grep include:
- Not quoting the pattern, which can cause shell expansion issues.
- Forgetting that
grepis case-sensitive by default. - Using
grepon binary files without options, which can produce unreadable output.
Here is a wrong and right way example:
bash
# Wrong: pattern not quoted, may cause errors if pattern has special chars grep apple fruits.txt # Right: pattern quoted to avoid shell issues grep 'apple' fruits.txt # Wrong: case-sensitive search misses 'Apple' grep 'apple' fruits.txt # Right: case-insensitive search finds both 'apple' and 'Apple' grep -i 'apple' fruits.txt
Quick Reference
| Option | Description |
|---|---|
| -i | Ignore case distinctions |
| -r | Search directories recursively |
| -v | Invert match (show lines NOT matching) |
| -n | Show line numbers with output |
| -c | Show count of matching lines only |
Key Takeaways
Use quotes around the pattern to avoid shell interpretation issues.
By default, grep is case-sensitive; use -i for case-insensitive search.
grep prints lines containing the pattern, making text search easy.
Use options like -r to search inside directories recursively.
Common mistakes include missing quotes and ignoring case sensitivity.