Categories
Linux

How to Use Grep Command in Linux

grep program is one of the most commonly used text processing programs in Linux. It is used to search for a substring or a string pattern in files.

Let us see how to use grep and what options are available.

Consider the contents of a text file:

cat test.txt
A quick brown dog jumped over the lazy fox.
Linux Operating System.

To search for string fox in this file, use:

grep fox test.txt

To invert the matching algorithm, i.e., to print non matching lines, use -v flag:

grep -v fox test.txt

To search for a pattern, use the -e flag:

grep -e "f.x" test.txt

To search without case sensitivity of the substring, use:

grep -i Fox test.txt

Finally, a very useful flag for grep command is -r. It recursively scans all files and directories till the last leaf in a directory structure.

I have copied the same file used above multiple times in a directory structure for providing an example.

To search recursively in all files and directories, use:

grep -r fox grep_test/

We hope you find the information on this page helpful. If you have any questions, get in touch with us on Twitter.

Leave a Reply