Reputation: 27
So what I have to do is find all regular files within and below the directory. For each of these regular files, I have to egrep for pattern($ARG) and find out if the output of the file matches the pattern ($ARG), if it does it will add one to the counter.
What I have so far is the file command:
$count = 0
file *
However, I am having trouble getting egrep &ARG > /dev/null/ ; echo $? to run through each file that appears from (file *).
I understand that file * | egrep directory > /dev/null ; echo $? will output 0 because it find the pattern 'directory' in the file, but am having trouble getting it to loop through each regular file so I can add one to the counter every time the pattern is matched.
Upvotes: 0
Views: 101
Reputation: 247192
See http://mywiki.wooledge.org/BashFAQ/020
counter=0
shopt -s globstar nullglob
for file in **; do
grep -qiE "$pattern" "$file" && ((counter++))
done
echo "$counter"
If you want to include hidden files, add shopt -s dotglob
Upvotes: 0
Reputation: 971
You can try this:
counter=0
find /path/to/directory/ -type f | \
while read file
do
if grep -i -e -q "$pattern" "$file"
then counter=$((counter+1))
fi
done
echo "$counter"
Upvotes: 0
Reputation: 67567
The question is not clear, but if you're looking for number of files containing a pattern
grep -l "pattern" * 2>/dev/null | wc -l
will give you that. Errors are ignored coming from directories.
If you want recursively do the complete tree including dot files
grep -r -l "pattern" | wc -l
Upvotes: 1