GREP stands for Globally Search a Regular Expression and Print. The basic usage of the command is
grep [options] expression filename. GREP will by default display any lines in a file that contain the expression. GREP command can be used to find or search a regular expression or a string in a text file. To demonstrate this, let’s create a text file "welcome_infogix.txt" and add some content as shown.
Now we are ready to perform a few grep commands and manipulate the output to get the desired results. Below are the syntax of the operation along with the output of the screenshot .
To search for a string in a file, run the command below
"string" file name grep
As you can see, grep has not only searched and matched the string “Linux” but has also printed the lines in which the string appears.
If the file is located in a different file path, be sure to specify the file path as shown below
Colorizing Grep results using the –color option
If you are working on a system that doesn’t display the search string or pattern in a different color from the rest of the text, use the
--color to make your results stand out.
Syntax : grep --color "string" filename
Searching for a string recursively in all directories
grep -r "string-name" *
Ignoring case sensitivity
Nothing from the output, right? This is because grepping could not find and match the string “linux” since the first letter is Lowercase. To ignore case sensitivity, use the
-i flag and execute the command below
grep -i "string" filename
Count the lines where strings are matched with -c option
"string" filenamegrep -c
Searching for a file name where the string is available
Syntax : grep -irl "string"
To number the lines where the string pattern is matched , use the
-n option as shown
grep -n "string" filename
Search for exact matching word using the -w option
This option only prints the lines with whole word matches and the names of the files it found them in:
To List Names of Matching Files
Sometimes, you only need to see the names of the files that contain a word or string of characters and exclude the actual lines. To print only the filenames that match your search, use the -l operator:
Syntax : grep -l linux *
Invert the Grep output ,
-v option instructs grep to print all lines that do not contain or match the expression.
Syntax: grep -v "string" filename
If you need to learn more on Grep command usage
run the command below to get a sneak preview of other flags or options that you may use together with the command.
Syntax: grep --help