Using the grep Command in Linux
The grep command in Ubuntu is a efficent text search utility used to find specific patterns within files or input provided via standard input. It stands for “Global Regular Expression Print.” grep is commonly used in combination with other commands and scripts to filter and search through text data.
Basic grep
Syntax
grep [options] pattern [file...]
pattern: The text pattern or regular expression you want to search for.
[file...]: One or more files to search within. If no file is specified, grep reads from the standard input.
grep
Examples and Usage
Basic grep
Usage Example
grep "error" /var/log/syslog
Explanation: This command searches for the word error
in the file /var/log/syslog
. It displays all lines containing the word.
Case-Insensitive Search
# Case sensitive
grep -i "example" file.txt
Explanation: This command will match lines containing example
, regardless of whether it is written as example
, EXAMPLE
, or any other capitalization.
Searching Recursively
grep -r "example" /path/to/directory
Search for “example” in all files within a directory and its subdirectories.
Count Number of Lines that Contain Specifi Word
grep -c "example" file.txt
This line will count the number of lines that contain “example” in the file file.txt.
Print N lines before or after pattern
-A (After Context):
Print N lines of trailing context after matching lines.
grep -A 3 "pattern" file
-B (Before Context):
Print N lines of leading context before matching lines.
grep -B 3 "pattern" file
-C (Context):
Print N lines of leading and trailing context around matching lines.
grep -C 3 "pattern" file
-E (Extended Regular Expressions):
Use extended regular expressions (like egrep).
grep -E "pattern1|pattern2" file
Other grep
Options
I very often use one of the following combinations with grep
-v (Invert Match):
Invert the match to select non-matching lines.
grep -v "pattern" file
-w (Word Match):
Match only whole words.
grep -w "pattern" file
-c (Count):
Count the number of matching lines.
grep -c "pattern" file
-l (Files with Matches):
List the names of files with matching lines.
grep -l "pattern" *.txt
-n (Line Number):
Show line numbers with output lines.
grep -n "pattern" file
-H (Show Filename):
Show the filename for each match (useful when searching multiple files).
grep -H "pattern" *.txt