Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash how to search for a string in all files in given directory using grep command [duplicate]

Tags:

bash

shell

my code till now is. I am a beginner.

count=0
for f in $ls do
count+= grep -c "classes" $f
done
echo $count
like image 466
Erwin Smith Avatar asked Aug 21 '17 16:08

Erwin Smith


People also ask

How do you grep for a string in all files in a directory?

To include all subdirectories in a search, add the -r operator to the grep command. This command prints the matches for all files in the current directory, subdirectories, and the exact path with the filename.

How do you find a string in all files in a directory in Unix?

You can use grep command or find command as follows to search all files for a string or words recursively.

How do you search for a string in all files recursively in Linux?

To recursively search for a pattern, invoke grep with the -r option (or --recursive ). When this option is used grep will search through all files in the specified directory, skipping the symlinks that are encountered recursively.


2 Answers

Just use

grep -R <stringToSearch> <dirName>

e.g to search "text" in current directory and all the files inside

grep -R "text" .

If you want to get number of occurrences use wc -l as pipe

grep -R "text" . | wc -l
like image 53
nagendra547 Avatar answered Oct 03 '22 04:10

nagendra547


grep -rnw <Directory_path> -e "Pattern"

Example, if you want to find "helloWorld" in all the files of the directory ~/abc/xyz, then run the following command-

grep -rnw ~/abc/xyz -e "helloWorld"

To search a string "HelloWorld" in the current directory, use the following command-

grep -rnw . -e "helloWorld"
like image 30
sachin teotia Avatar answered Oct 03 '22 05:10

sachin teotia