grep command lets you quickly locate lines that match a specified string or regular expression.
Table of Common Options
| Option | Description | Example |
|---|---|---|
| -i | Ignore case (case-insensitive search) | grep -i 'error' logfile.txt |
| -r | Recursive search in all subdirectories | grep -r 'TODO' /home/user/projects |
| -v | Invert match (show non-matching lines) | grep -v 'DEBUG' app.log |
| -w | Match whole words only | grep -w 'user' /etc/passwd |
| -o | Show only the part of a line that matches | grep -o '[0-9]\+' data.txt |
General Syntax
- PATTERN
The text or regular expression to search for. - FILE
One or more files or directories to scan. If no file is given,grepreads from standard input.
Always quote patterns that contain spaces or shell metacharacters:
1. Basic, Case-Sensitive Search
By default,grep performs a case-sensitive search. To find lines containing CentOS in /etc/os-release:
2. Case-Insensitive Search
Use-i to ignore case differences. This matches “centos”, “CentOS”, or “CENTOS” alike:
3. Recursive Search in Directories
To search through all files in a directory and its subdirectories, combine-r with your pattern:
-r and -i for a recursive, case-insensitive search:
You may encounter “Permission denied” messages when scanning protected directories. Use
sudo if you need elevated privileges:4. Invert Match
Show only the lines that do not contain the pattern. Use the-v option:
5. Match Whole Words Only
To avoid matching substrings (e.g., “redhat” when you want “red”), add the-w flag:
6. Show Only the Matched Text
By default,grep prints the entire line containing the match. Use -o to display only the portion that matches:
You’ve now covered the essentials of
grep for searching text in files. In upcoming lessons, we will explore more advanced text-processing tools like awk and sed.