Lesson 27: fgrep Command
In this lesson, you'll learn how to use the fgrep command to search for fixed string patterns in files in Linux.
The fgrep command in Linux falls under the family of the grep command. However, it is used to search for the fixed string pattern instead of regular expressions. Hence, the name of the command is fgrep (Fixed GREP).
fgrep Command Syntax
The syntax of the fgrep command is similar to the other grep family commands:
$ fgrep [OPTIONS] PATTERNS [FILES]
fgrep Command Options
| Option | Description |
|---|---|
-f FILE |
Read patterns from a file, one per line |
-m N |
Limit the number of matching lines to N |
-l |
Print only the names of files with matching lines |
-L |
Print only the names of files with no matching lines |
-s |
Suppress error messages for non-existing or unreadable files |
-x |
Match only the entire line exactly |
-n |
Display line numbers with matching lines |
-r |
Search recursively in all subdirectories |
--exclude PATTERN |
Exclude files matching a pattern during recursive search |
--exclude-from FILE |
Read exclude patterns from a file |
--include PATTERN |
Include only files matching a pattern during recursive search |
To begin, let's create a plain text file with the following contents to use as an example:
$ cat input.txt
TecMint is the best Linux resource website on the internet.
TecMint was started on 15th August 2012 by technical professionals and all the
articles and contents are written by talented professionals around the globe,
keeping in high importance on quality, comprehensiveness, and usefulness goes
into each of the articles published.
The website covers topics like Linux commands, shell scripting, and more.
Sometimes the same site is sometimes hard to find.
Here, we can see that the text file is ready with the sample contents. Now, let's discuss some common examples of the fgrep command in the next few examples.
1. How fgrep Differs from grep and egrep
As the name suggests, the fgrep command is used to search for fixed string patterns. It interprets the pattern as a fixed string instead of a regular expression.
Hence, it performs the search operation in a time-efficient way.
To understand the difference, let's use a dot (.) character with the grep command. This simple regular expression matches any single character except for the end of the line:
$ grep ha. input.txt
TecMint was started on 15th August 2012 by technical professionals and all the
In the above output, we can see that the dot (.) character matches the text har, hat, and has.
Now, let's use the same pattern with the fgrep command and observe the result:
$ fgrep ha. input.txt
In the above output, we can see that the command fails to find the given pattern. This happens because the fgrep command doesn't recognize regular expressions and tries to search for the non-existing pattern "ha.".