The grep
command is part of the GNU Core-utilities package and filters text files for a given character arrangement or pattern.
The GNU Core-utilities package is available on all Unix-like operating systems.
The grep
command supports many functionalities. Users can select a functionality of their choice by setting the right flags or arguments. In this shot, we go through the most frequently used arguments for grep
.
The -c
flag is used to output the number of lines in file.txt that contain the word pattern
as a string or sub-string.
The -i
flag makes sure that grep
performs a case-insensitive search. It displays all the lines in file.txt that contain the word paTTern
, regardless of the alphabetical case as a string or sub-string.
The -l
flag outputs the name of all those files containing text with the word pattern
in it as a string or sub-string.
The -w
flag is used to output all those lines in file.txt containing pattern
as a whole word and not as a sub-string.
The o
flag displays only the matched pattern instead of displaying the entire string or line which contains it.
The -n
flag outputs the line number of the lines containing pattern
alongside the line itself.
The -v
flags invert the search results, as it displays those strings in file.txt which do not contain pattern
.
The ^
operator is used to output all those lines in file.txt which have pattern
as their first word.
The --help
flag is used to open the manual page of grep
, which contains additional information about it.
In the example below, we use the echo
command to create a text file, and write Educative!
, Edpresso
, and Sadzub
on lines 1, 2, and 3, respectively.
Subsequently, we use the -i
flag to run a case-insensitive search for the sub-string EDUCative
in our text file and print the string which contains it. Additionally, we use the -n
flag to print the line number of the line, which contains EDUcative
and zub
.
Searching for
Zub
would not yield any results because the-n
flag runs a case-sensitive search.
Last but not least, we use the -o
flag to print the matched pattern itself, i.e., Educative
.
Note that for the
-o
flag, there is no exclamation mark at the end of the output.
Free Resources