The grep
command is used to search for text patterns within files or output streams in Linux. It supports regular expressions and various options to refine searches.
Options | Description | Example |
---|---|---|
-v | Exclude a specific word. | 2, 4 |
-c | Count occurrences of a word. | 3, 4 |
-i | Ignores, case for matching. | 5, 6 |
-n | Matched lines and their line numbers. | 6 |
-r | Search for a word in all files within a directory (recursive) | |
-l | Displays list of a filenames only. | |
-w | Match whole word | 1 |
-o | Print only the matched parts of a matching line, with each such part on a separate output line. | |
-E | PATTERNS are extended regular expressions |
Basic Usage
1. Search for a specific word in a file
Note
grep "Alice" text.txt
andgrep -w "Alice" text.txt
, both command will produce same Output.
grep "Alice" text.txt
2. Exclude a specific word (invert match)
grep -v Alice text.txt
3. Count occurrences of a word
grep -c Alice text.txt
4. Count lines that do not contain the word
grep -cv Alice text.txt
5. Case-insensitive search
grep -i Alice text.txt
6. Matched lines and their line numbers.
grep -in alice text/text.txt
7. Print only the matched parts of a matching line, with each such part on a separate output line.
grep -io alice text/text.txt
8. Using expression multiple times
grep -e "Alice" -e "is" text/text.txt
Recursive Search
1. Search for a word in all files within a directory (recursive)
grep -ri "Alice" text/
2. List only filenames containing the word
grep -ril "Alice" text/
Pattern Matching
1. Search for lines starting with a specific word
grep "^The" text/text.txt
2. Search for lines ending with a specific character (e.g., s.
)
grep -i "s.$" text/text.txt
3. Count empty lines in multiple files
grep -rc "^$" text/
4. Search for lines containing a specific pattern
grep ".or" text/text.txt
grep "....or" text/text.txt
Custom Commands
1. Search for email addresses
grep -E "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}" text.txt
2. Find all dates (YYYY-MM-DD format)
grep -E "[0-9]{4}-[0-9]{2}-[0-9]{2}" text.txt
3. Find IP addresses
grep -E "([0-9]{1,3}\.){3}[0-9]{1,3}" text.txt
4. Find lines with currency symbols ($, £, €)
grep -E "[$£€][0-9]+" text.txt
5. Extract phone numbers
grep -E "\+?[0-9]{1,3}[- ]?[0-9]{3,4}[- ]?[0-9]{4,}" text.txt
6. Find hexadecimal color codes
grep -E "#[A-Fa-f0-9]{6}" text.txt
7. Find file paths (both Linux and Windows)
grep -E "(/[^ ]+|\w:\\\\[^ ]+)" text.txt
The grep
command is a powerful text-searching tool in Linux, allowing users to find, count, and filter text patterns efficiently.