Key Options
Combine various `grep` command options to search for your desired text.
1. Basic Search
2. Search Options
3. Output Options
4. Recursive Search
Generated command:
Try combining the commands.
Description:
`grep` Executes the command.
Combine the above options to virtually execute commands with AI.
Regular Expression Basics
The `grep` command supports Regular Expressions for powerful text searching. Using regular expressions allows you to easily find complex patterns.
| Character | Description | Example |
|---|---|---|
| . | Any single character (except newline) |
a.b (acb, amb, etc.)
|
| * | The preceding character zero or more times |
ab*c (ac, abc, abbc, etc.)
|
| + | The preceding character one or more times |
ab+c (abc, abbc, etc.)
|
| ? | The preceding character zero or one time |
ab?c (ac, abc)
|
| ^ | Start of a line |
^start (lines beginning with 'start')
|
| $ | End of a line |
end$ (lines ending with 'end')
|
| [abc] | Any one of the characters in the brackets |
[aeiou] (vowels)
|
| [a-z] | Any character within the specified range |
[0-9] (digits)
|
| [^abc] | Any character NOT in the brackets |
[^0-9] (non-digit characters)
|
| \b | Word boundary |
\bword\b (exactly the word 'word')
|
| | | OR operator (either of two patterns) |
cat|dog ('cat' or 'dog')
|
Basic Regular Expressions (BRE) and Extended Regular Expressions (ERE)
grep uses BRE by default. To use characters like +, ?, |, (, ) with special meaning, you must escape them with a backslash (\). Using the -E option enables ERE mode, allowing these characters to be used without backslashes. The -P option provides more powerful PCRE.
Usage Examples
Practice text searching through practical examples of the `grep` command.
Search for 'error' in a log file
grep 'error' /var/log/syslog
Prints all lines containing the string 'error' in the `syslog` file.
Case-insensitive search for 'failed' and print line numbers
grep -in 'failed' /var/log/auth.log
Searches for 'failed' regardless of case and displays line numbers with the results.
Print lines that do not contain a specific pattern
grep -v '^#' /etc/nginx/nginx.conf
Prints lines from `nginx.conf` file, excluding lines that start with a hash (#) (comments).
Search for 'server_name' in '.conf' files including subdirectories
grep -r 'server_name' *.conf
Recursively searches for the 'server_name' pattern in files with a '.conf' extension in the current directory and all its subdirectories.
Find a specific process (using ps and pipe)
ps aux | grep apache2
Filters and displays only 'apache2' related processes from the output of the `ps aux` command.
Search for 'warning' or 'critical' in multiple files
grep -E 'warning|critical' /var/log/syslog /var/log/kern.log
Uses the regular expression OR (|) operator to search for 'warning' or 'critical' messages in multiple log files.