Linux Command Series: The Powerful Text Search Tool grep

This article provides a detailed introduction to the usage of the grep command, including common options, regular expression applications, and more. Let’s learn together and improve together! Continue reading!First, what is grep?grep is a command in the Linux system used to search for text within files, useful for various text processing and log analysis. I often use it in production to check logs, as the logs can be overwhelming, and grep, combined with the find command, works exceptionally well. grep stands for “Global Regular Expression Print,” meaning “global regular expression print.” The power of grep lies in its ability to efficiently search for matching content in files or outputs and return the lines that meet the criteria.1. Basic Syntax of grep

grep [options] pattern [file...]
  • pattern: The pattern to search for (can be a plain string or a regular expression).
  • file: The file(s) to search (can be omitted; if omitted, `grep` will read data from standard input (stdin)).

2. Common Options

  • -i: Ignore case (case-insensitive search).
grep -i "hello" filename
  • -v: Invert match, output lines that do not contain the specified pattern.
grep -v "error" log.txt
  • -r or -R: Recursively search files in directories and subdirectories.
grep -r "pattern" /home/kangn/data
  • -l: Only display the names of files containing the matching pattern, not the matching lines.
grep -l "pattern" *.txt
  • -n: Display the line numbers of matching lines.
grep -n "pattern" file.txt
  • -c: Count the number of matching lines.
grep -c "pattern" file.txt
  • -H: Display the filename of matching lines (even when searching a single file, the filename is displayed).
grep -H "pattern" file.txt
  • -o: Only output the matching part, not the entire line.
grep -o "pattern" file.txt
  • -w: Match whole words, not parts of words.
grep -w "pattern" file.txt
  • -x: Only match whole lines, returning only when the line content exactly matches the pattern.
grep -x "exact line" file.txt
  • -A: Display matching lines and the following N lines.
grep -A 3 "pattern" file.txt
  • -B: Display matching lines and the preceding N lines.
grep -B 3 "pattern" file.txt
  • -C: Display matching lines and N lines before and after (context).
grep -C 3 "pattern" file.txt

3. Regular Expressions and grepThe power of grep lies in its support for using regular expressions for complex pattern matching. You can enable regular expressions in the following two ways:

  • grep (basic regular expressions): By default, it uses basic regular expressions.
  • egrep (extended regular expressions): egrep is shorthand for grep -E, supporting extended regular expressions.

Common regular expression symbols:

  • ‘.’: Matches any single character (except newline).
grep "a.b" file.txt  # Matches lines containing "a" and "b" with any character in between, such as "a1b", "acb", etc.
  • `*`: Matches the preceding character zero or more times.
grep "a*b" file.txt  # Matches "b", "ab", "aab", "aaab", etc.
  • `^`: Matches the start of a line.
grep "^hello" file.txt  # Matches lines starting with "hello"
  • `$`: Matches the end of a line.
grep "world$" file.txt  # Matches lines ending with "world"
  • `[]`: Matches any one of the characters in the brackets.
grep "a[aeiou]b" file.txt  # Matches lines where "a" is followed by a vowel and then "b"
  • `[^]`: Matches characters not in the brackets.
 grep "a[^aeiou]b" file.txt  # Matches lines where "a" is followed by a non-vowel and then "b"
  • `()`: Groups, usually used with `\` to indicate extended regular expressions.
grep "\(abc\)\{2\}" file.txt  # Matches lines where "abc" appears consecutively twice

Extended regular expressions:In `grep -E` or `egrep`, extended regular expressions support more special characters, such as `+`, `?`, `{}`, `|`, etc.

egrep "a+b" file.txt  # Matches lines with at least one "a" followed by a "b"

4. Using Pipes with grepgrep is often used in combination with other commands, especially in pipes. It can filter the output of other commands, helping you quickly extract information.For example, to view all files in the current directory that contain a certain keyword:

ls | grep "pattern"

5. Example: Using `grep` to Search LogsSuppose you have a log file named `system.log` and want to find all lines containing “error” and display the line numbers, you can use the following command:

grep -n "error" system.log

If you only want to find the filenames containing “error” without displaying the line content, you can use:

grep -l "error" *.log

6. Advanced Usage: Finding Multiple PatternsYou can use the `-e` option to search for multiple patterns:

grep -e "pattern1" -e "pattern2" file.txt

Using grep with find will be more efficient and interesting; for those who are not familiar with find, you can refer to the article “Linux Command Series: find”. The author’s introduction is not detailed enough, and there are too many usages to list them all, so please bear with me!

Leave a Comment