grep (Global Regular Expression Print)
grep is a command-line utility for searching plain-text data sets for lines that match a regular expression. It is one of the most essential tools for developers and system administrators to filter through logs and command outputs.
1. Basic Usage
grep [options] "pattern" [file]
2. Key Options
| Option | Name | Description |
|---|---|---|
-i |
ignore-case | Ignore case. Performs case-insensitive matching. |
-v |
invert-match | Invert match. Selects non-matching lines (exclude lines). |
-r |
recursive | Recursive. Searches through all files under each directory. |
-n |
line-number | Line number. Prefixes each line of output with its line number. |
-c |
count | Count. Prints only a count of matching lines. |
-E |
extended-regexp | Extended regex. Interprets the pattern as an extended regular expression (ERE). |
3. Practical Examples
① Searching for a string in a file
grep "failed" /var/log/syslog
② Filtering command output with Pipes (|)
Find if a specific service is running:
ps -ef | grep nginx
③ Searching for a string in multiple files recursively
grep -r "TODO" ./src/
④ Excluding patterns
Show log entries except those containing "INFO":
grep -v "INFO" access.log
4. [Tip] Basic Regex Patterns
^text: Matches the beginning of a line.text$: Matches the end of a line.[0-9]: Matches any single digit.\.: Matches a literal dot (escaping).