How To Use grep Command In Linux

How To Use Grep Command In Linux

Grep is an essential Linux and Unix command. It is used to search text and strings in a given file. In other words, grep command searches the given file for lines containing a match to the given strings or words.

The syntax is as follows:

grep 'word' filename
fgrep 'word-to-search' file.txt
grep 'word' file1 file2 file3
grep 'string1 string2'  filename
cat otherfile | grep 'something'
command | grep 'something'
command option1 | grep 'data'
grep --color 'data' fileName
grep [-options] pattern filename
fgrep [-options] words file


How to use grep recursively

You can search recursively i.e. read all files under each directory for a string “”

$ grep -r "" /etc/


$ grep -R "" /etc/

Sample outputs:

/etc/ppp/options:# ms-wins
/etc/ppp/options:# ms-wins
/etc/NetworkManager/system-connections/Wired connection 1:addresses1=;24;;

You will see result for on a separate line preceded by the name of the file (such as /etc/ppp/options) in which it was found. The inclusion of the file names in the output data can be suppressed by using the -h option as follows:

$ grep -h -R "" /etc/


$ grep -hR "" /etc/

Sample outputs:

# ms-wins
# ms-wins