
Preface
grep is one of the Linux trio (grep, sed, awk), used to search for specific text patterns in files. It is not only powerful but also very flexible, capable of handling a wide variety of text-search needs. Below we walk through the detailed usage of the grep command and its advanced examples.
Basic Usage
Basic Search
| |
Used to search the filename file for lines containing pattern and print them out.
Ignoring Case
| |
Use the -i option to ignore case.
Recursive Search
| |
Recursively search the contents of files containing pattern in the directory and its subdirectories.
Showing Line Numbers
| |
Use the -n option to show the line numbers of matching lines.
Inverted Search (Show Non-Matching Lines)
| |
Use the -v option to show lines that do not contain pattern.
Showing File Names
| |
When searching multiple files, the matching file names are shown by default. Use -H to force showing file names, and use -h to hide them.
Advanced Usage
Using Regular Expressions
| |
Use the -E option to support extended regular expressions, where | means the OR operation.
Counting Matching Lines
| |
Use the -c option to count the number of matching lines.
Showing Only the Matched Part
| |
Use the -o option to show only the matched part instead of the entire line.
Showing Lines Before and After
| |
The -A, -B, and -C options are used to show a specified number of lines after, before, or both before and after the matching line, respectively.
Reading Data from Standard Input
| |
grep can read data from standard input, which is very useful in pipeline operations.
Searching with Fixed Strings (Improving Performance)
| |
Use the -F option to treat pattern as a fixed string rather than a regular expression, which can improve search performance.
Excluding Files
| |
Use the --exclude option to exclude files of a certain type.
Using Perl-Compatible Regular Expressions
| |
Use the -P option to enable Perl-compatible regular expressions, where \d+ means one or more digits.
Zero-Width Assertions
| |
Use Perl-compatible regular expressions to support zero-width assertions; for example, (?<=foo)bar matches a bar that is preceded by foo.
Combined Usage Examples
Finding Files of a Specific Type in a Specific Directory and Searching Their Contents
| |
Recursively search all .py files in the /path/to/directory directory for lines containing import.
Finding and Showing Matching Lines with Two Lines Before and After
| |
Find lines containing error in the /var/log/syslog file and show the two lines before and after them.
Counting the Number of Files Containing a Specific Word
| |
Recursively search the /path/to/directory directory for files containing word, and count the number of files.
Conclusion
Through these examples, you can appreciate the power and flexibility of grep, which also makes it one of the most practical text-processing tools in Linux.
