How to Search in a File on Linux Using grep Command
To search for text inside a file on Linux, use the
grep command followed by the search pattern and the file name, like grep 'text' filename. This command prints all lines containing the specified text from the file.Syntax
The basic syntax of the grep command is:
grep 'pattern' filename: Searches for the exact pattern inside the given filename.-i: Makes the search case-insensitive.-r: Recursively searches inside directories.-n: Shows line numbers where matches occur.
bash
grep 'pattern' filename grep -i 'pattern' filename grep -r 'pattern' directory/ grep -n 'pattern' filename
Example
This example shows how to search for the word error inside a file named log.txt. It prints all lines containing error exactly as they appear.
bash
grep 'error' log.txt
Output
Error: failed to connect to server
Critical error in module 3
No error found in this line
Common Pitfalls
Common mistakes when using grep include:
- Not quoting the search pattern, which can cause shell interpretation issues.
- Forgetting that
grepis case-sensitive by default. - Trying to search directories without
-roption.
Example of wrong and right usage:
bash
grep error log.txt # May fail if shell treats 'error' specially # Correct way with quotes and case-insensitive search grep -i 'error' log.txt
Quick Reference
| Option | Description |
|---|---|
| grep 'pattern' filename | Search for pattern in a file |
| grep -i 'pattern' filename | Case-insensitive search |
| grep -r 'pattern' directory/ | Search recursively in directory |
| grep -n 'pattern' filename | Show line numbers with matches |
| grep -v 'pattern' filename | Show lines NOT matching pattern |
Key Takeaways
Use
grep 'pattern' filename to find text inside files on Linux.Add
-i for case-insensitive searches and -r to search directories recursively.Always quote your search pattern to avoid shell issues.
Use
-n to see line numbers where matches occur.Remember
grep is case-sensitive by default.