Grep command in linux

Grep command in linux

·

2 min read

Grep(global regular expression print) command is used in Linux to find and search using regular expressions throughout the Linux system.

syntax: grep 'string' filename

or

syntax: filename grep 'string'

eg -> grep -i 'warning' logfile.txt

To search recursively in all the directories -r option

grep 'config' -r /etc/nginx

In the above command, we're finding a config file inside the /etc/nginx directory. By using -r, it will find all the sub-directories inside the nginx directory

To count the lines where strings are matched with -c option

grep -c 'INFO' logfile.txt

This command will display the number of lines in which the INFO text is present in the logfile.txt

To display the line number where the search pattern contains with -n option

grep -n 'WARNING' logfile.txt

To ignore case sensitivity with the -i option

grep -i 'info' logfile.txt

To invert the output of a file with the -v flag

grep -vi 'info' logfile.txt

This will print everything on the console that doesn't contain info

Redirecting the results from other commands to grep by using pipe |

dpkg -l | grep 'package-name'

eg -

dpkg -l | grep "chrome"

here dpkg command will list the install packages inside the Linux system and with the help of pipe we check that the Chrome browser is installed in the system

grep with REGEX

A REGEX or REgular EXpression is a sequence of characters that is used to match pattern.

eg ->

^      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

To print certain characters from a file

syntax - grep ^character filename

To display the lines begin with the number "0" in our logfile.txt file

grep ^0 logfile.txt

To display the lines end with character "p"

grep p$ logfile.txt

Colorizing grep results with --color flag

If you're working on a system that doesn't display the search pattern in a different color then use --color flag.

grep --color 'INFO' logfile.txt

For more grep options

If you need to learn more about grep command usage, then use --help will display the usage of all flags and options that can be used with the grep command.

grep --help

Thank you