Open In App

fgrep command in Linux with examples

The fgrep filter is used to search for the fixed-character strings in a file. There can be multiple files also to be searched. This command is useful when you need to search for strings which contain lots of regular expression metacharacters, such as “^”, “$”, etc.

Syntax:



fgrep [options] [ -e pattern_list] [pattern] [file]

Options with Description:

Below are the examples with options to illustrate the fgrep command:



Consider below file as input. Here it is create using cat command and “name of the file is para”.

Hi, @re you usin.g geeks*forgeeks for learni\ng computer science con/cepts.
Geeks*forgeeks is best for learni\ng.

-c option: Displaying the count of number of matches. We can find the number of lines that match the given string.

Example:

$fgrep -c "usin.g" para

Output:

1

-h option: To display the matched lines.

Example:

 fgrep -h "usin.g" para

Output:

Hi, @re you usin.g geeks*forgeeks for learni\ng computer science con/cepts.

-i option: Used in case insensitive search. It ignore upper/lower case distinction during comparisons. It matches words like : “geeks*forgeeks”, “Geeks*forgeeks”.

Example:

 fgrep -i "geeks*forgeeks" para

Output:

Hi, @re you usin.g geeks*forgeeks for learni\ng computer science con/cepts.
Geeks*forgeeks is best for learni\ng.

-l option: It will display the file names that match the pattern. We can just display the files that contains the given string/pattern.

Example:

fgrep -l "geeks*forgeeks" para para2

Output:

para

-n option: Precede each line by its line number in the file. It shows line number of file with the line matched.

Example:

$ fgrep -n "learni\ng" para

Output:

1:Hi, @re you usin.g geeks*forgeeks for learni\ng computer science con/cepts.
2:Geeks*forgeeks is best for learni\ng.

-v option: It is used to display all lines except those that contain the pattern. It will print all lines except those that contain the pattern.

Example:

fgrep -v "@re" para

Output:

Geeks*forgeeks is best for learni\ng.

-x option: It will display only lines matched entirely.

Example 1:

fgrep -x "@re" para

Output:

 

Example 2:

fgrep -x "Geeks*forgeeks is best for learni\ng." para

Output:

Geeks*forgeeks is best for learni\ng.

Article Tags :