56

my code till now is. I am a beginner.

count=0
for f in $ls do
count+= grep -c "classes" $f
done
echo $count
Erwin Smith
  • 761
  • 2
  • 6
  • 8

4 Answers4

114

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
nagendra547
  • 5,672
  • 3
  • 29
  • 43
14
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"
4castle
  • 32,613
  • 11
  • 69
  • 106
sachin teotia
  • 141
  • 2
  • 2
2

I believe find will be the BEST option for this requirement, could you please try following and let me know if this helps you.

find . -type f  -exec grep -i "test" {} + | wc -l
OR
find . -type f  | xargs grep -i "test" | wc -l

You could mention your path in place of DOT above too.

RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
0
count=0
for f in *
do
if [ -f "$f" ] #check if that file is regular file
then
    count=$(($count+$(grep -c "classes" "$f")))
fi
done
echo $count
tso
  • 4,732
  • 2
  • 22
  • 32
  • `grep: all: No such file or directory grep: it: No such file or directory grep: takes.jpg: No such file or directory ./script8: line 4: 0+: syntax error: operand expected (error token is "+") 0 ` – Erwin Smith Aug 21 '17 at 16:36
  • all it takes.jpg is a file in my directory + the answer should be 13 – Erwin Smith Aug 21 '17 at 16:38
  • seems like you can help me with this too https://stackoverflow.com/questions/45799657/bash-adding-a-string-to-file-name – Erwin Smith Aug 21 '17 at 16:43
  • `grep: untitled folder: Is a directory ./script8: line 4: 8+: syntax error: operand expected (error token is "+") 8` – Erwin Smith Aug 21 '17 at 16:44
  • You must say that there are also directories in your current directory. :3 have edited answer – tso Aug 21 '17 at 16:49