Linux - Understanding the grep Command in Linux
The grep command stands for Global Regular Expression Print. It is one of the most commonly used commands in Linux for searching text patterns inside files or output from other commands. It helps users find lines that contain a specific keyword, phrase, or regular expression.
What does grep do?
grep scans through one or more files and prints all lines that match a given pattern. It is useful for:
-
Searching log files
-
Finding specific configuration details
-
Filtering command outputs
-
Matching patterns using regular expressions
Basic Syntax
grep [options] "pattern" filename
Common Examples
1. Search for a word in a file
grep "error" logfile.txt
Shows all lines containing the word "error".
2. Case-insensitive search
grep -i "error" logfile.txt
Matches error, Error, ERROR, etc.
3. Recursive search in directories
grep -r "config" /etc/
Searches for the word "config" in all files under /etc.
4. Show line numbers of matches
grep -n "root" /etc/passwd
Displays the matching lines with line numbers.
5. Count matching lines
grep -c "failed" auth.log
Shows how many lines contain the word "failed".
6. Show only the matched word
grep -o "admin" users.txt
Prints only the matched word.
7. Match whole words only
grep -w "cat" animals.txt
Matches "cat" but not "category".
Useful Options
| Option | Description |
|---|---|
| -i | Ignore case |
| -r | Recursive search |
| -n | Show line numbers |
| -c | Count matches |
| -w | Match whole words |
| -v | Show non-matching lines |
| -o | Show only matched text |
| -E | Use extended regular expressions |
Using grep with Pipes
ps aux | grep "apache"
Finds processes related to "apache".