Search through files using the grep command in linux

The grep command is one of the most powerful commands in Linux. It is used for searching a pattern inside files. The pattern can range from a simple alphabet to a complex regular expression. There are various scenarios where grep can be useful. We will try to list some of them in this post.

List all the lines in a file that contain the word

grep -i 'hello world' main.txt

The -i option is used to ignore case distinctions i.e makes the search case insensitive. The above command will try to find the lines in the file main.txt that contain the word 'hello world'.

We may give more than 1 file if we need.

grep -i 'hello world' main.txt main.c

List just the name of the matching files

grep -l 'main' *.py

This will list all Python modules (*.py files) inside the current directory that contain the word main inside them.

List the name of the matching files alongside the matching lines
grep -H 'main' *.py

Search recursively inside directories

grep -r 'hello' /home

Both -r and -R specify the search to be recursive, except the fact that -R also follows symlinks.

Search recursively only through files that match a particular pattern

grep -ir 'main' include='*.cpp' /home

This will look recursively but only inside the C++ files(end with .cpp)

Search only for a word

Our last search would even match with word 'mains' or 'really_main' but if we want it to just match a word not just a part of the word, we can use the option -w

grep -irw 'main' include='*.cpp' /home

For more control, you may use the  \<, \> to match the start and end of words. For example

grep '\<main' *

will search only for the words starting with main. So this will match the word 'mains' but not 'really_mains'.

List the file names with no matching lines

grep -L 'import' *.py

Invert the match

grep -v 'import' *.py

Count the number of lines when the word matches

grep -c 'import' *.py
Print the line number alongside the matched line
grep -n 'import' *.py
Print the context around matching lines
grep -C 2 'math.log' *.py

This will print 2 lines of context around each matching line.

Using Regular Expression

grep -e '[[:digit:]]' info.txt

The -e option is used to specify regular expression patterns. In this case, the pattern is a digit. You can use more complex expressions according to your needs.

Using pipes to redirect output from another command

tail /var/log/apache2/error.log | grep -e '[[:digit:]]'

These were some of the use cases that we thought could be useful for you when learning about the grep command. It can help you in saving time, especially when searching through a chunk of files. We hope it helps you swim to deeper depths into the world of Linux. We just want to make this journey an enjoyable experience for you. Incase you are interested in knowing about other linux commands, you may visit this page.

Till, we meet again in another blog, keep hacking !!!


Login to join the discussion