Grep command

The grep command and flags explained

Last Update Unknown

Grep

The grep command can be used to find or search a regular expression or a string in a text file.

To search for a string in a file, run the command below:


Searching for a string recursively in all directories

If you wish to search for a string in your current directory and all other subdirectories, search using the - r flag as shown


Ignoring case sensitivity

In the above example, our search results gave us what we wanted because the string “Linux” was specified in Uppercase and also exists in the file in Uppercase. Now let’s try and search for the string in lowercase.


Count the lines where strings are matched with -c option

To count the total number of lines where the string pattern appears or resides, execute the command below


Using Grep to invert Output

To invert the Grep output , use the -v flag. The -v option instructs grep to print all lines that do not contain or match the expression. The –v option tells grep to invert its output, meaning that instead of printing matching lines, do the opposite and print all of the lines that don’t match the expression.


Number the lines that contain the search pattern with -n option

To number the lines where the string pattern is matched , use the -n option as shown


Search for exact matching word using the -w option

Passing then -w flag will search for the line containing the exact matching word as shown


Using pipes with grep

The grep command can be used together with pipes for getting distinct output. For example, If you want to know if a certain package is installed in Ubuntu system execute


Displaying number of lines before or after a search pattern Using pipes

You can use the -A or -B to dislay number of lines that either precede or come after the search string. The -A flag denotes the lines that come after the search string and -B prints the output that appears before the search string. For example

Conversely, in the example below, the use of the -B flag will display the line containing the search string plus 3 lines of text before the ether string in the ifconfig command.

You can use the -C to display the number of lines that precede and come after the search string.


Using grep with regular expressions (REGEX)

^      Matches characters at the beginning of a line

$      Matches characters at the end of a line

"."    Matches any character

[a-z] Matches any characters between A and Z

[^ ..] Matches anything apart from what is contained in the brackets

Regex can be used with grep to match a pattern. For instance, to display the lines that begin with the letter “d” in our welcome.txt file, we would execute

You can use the -E to allow for the use of extended regex in your standard grep searches! grep -E is also equivalent to egrep

The above commands would find all the words which start with "tele" from /usr/share/dict/words, and which are exactly 7 characters long.