How to use grep command to search for a word in Sub Directories

grep command is used to search for a word or character steam in files. We can use grep to search for multiple files with in a given directory by using below command

grep ‘search-term’ *

Where * will be replaced by each file in a given directory by your Shell.

But is it possible to search with in subdirectories as well?
Yes, we can do that by using grep -r(for recoursely) and -l (for listing files) as shown below.

grep -rl “searchterm” foldername

Example: I want to search for ‘abc’ in all the files in present working directory as well as sub directories, I used below command.

grep -rl for .

./.chphome
./.bash_history
./.viminfo
./scripts/profilefind.sh
./scripts/temp2/firstfor.sh
./scripts/temp2/secondfor.sh
./scripts/forandtest.sh
./moveprof.sh
./perlscripts/moveprof.sh
./perlscripts/chomptest.pl
./perlscripts/wout1.pl

hope this helps when search sub directories.

The following two tabs change content below.
Mr Surendra Anne is from Vijayawada, Andhra Pradesh, India. He is a Linux/Open source supporter who believes in Hard work, A down to earth person, Likes to share knowledge with others, Loves dogs, Likes photography. He works as Devops Engineer with Taggle systems, an IOT automatic water metering company, Sydney . You can contact him at surendra (@) linuxnix dot com.