The grep family of commands in Linux is used for
searching text using patterns. The most common member
is grep, but there are several variations, each with its own
specific use cases. Let’s explore the most common ones:
grep, egrep, fgrep, and zgrep.
1. grep
The grep command stands for "Global Regular
Expression Print." It searches for a specified pattern in
files and outputs the lines that match.
Basic Syntax:
grep [options] pattern [file...]
Example:
grep "hello" myfile.txt
This command searches for the string "hello" in
myfile.txt and prints the matching lines.
Common Options:
• -i: Ignore case (case insensitive)
• -v: Invert match (show lines that do not match)
• -r: Recursive search in directories
• -n: Show line numbers with output
• -l: Show only file names with matches
Example with Options:
grep -i "hello" myfile.txt
This searches for "hello", ignoring case.
2. egrep
egrep stands for "Extended Global Regular Expression
Print." It is similar to grep but supports extended regular
expressions, which allow for more complex pattern
matching.
Basic Syntax:
egrep [options] pattern [file...]
Example:
egrep "hello|world" myfile.txt
This searches for lines containing either "hello" or
"world".
Common Options: The options for egrep are the same as
for grep, but you can use +, ?, {} etc., in your patterns.
3. fgrep
fgrep stands for "Fixed Global Regular Expression
Print." It searches for fixed strings (literal matches) rather
than using regular expressions. This makes it faster when
you're searching for exact strings.
Basic Syntax:
fgrep [options] string [file...]
Example:
fgrep "hello*" myfile.txt
This will look for the exact string "hello*" and will not
treat the asterisk as a special character.
4. zgrep
zgrep is used for searching compressed files (e.g., .gz
files). It operates like grep but decompresses the files on-
the-fly.
Basic Syntax:
zgrep [options] pattern [file...]
Example:
zgrep "hello" myfile.gz
This searches for "hello" in the compressed file
myfile.gz.
Summary of Usage
Command Use Case
grep Basic pattern search
egrep Extended regex patterns
fgrep Fixed string search
zgrep Search in compressed files
Practical Example
Suppose you have a log file server.log and you want to
find error messages.
1. Using grep:
grep "ERROR" server.log
2. Using egrep (for multiple patterns):
egrep "ERROR|WARNING" server.log
3. Using fgrep:
fgrep "200 OK" server.log
4. Using zgrep:
zgrep "ERROR" server.log.gz