Home > Software engineering >  How to find whether any file of a directory contains a specific string using bash script?
How to find whether any file of a directory contains a specific string using bash script?

Time:04-21

I need to check if the string M1039C28 is inside any file of the directory /var/opt.
It should echo true if the string is found or echo String not found if the string is not found.

Sample:

cd /var/opt/;
if [ find ./ -type f -exec grep -Hni "M1039C28" {} ';']
then
    echo "String found"
else
    INFO "String not found"
fi

CodePudding user response:

Consider using grep with options -q (true / false behaviour) and -r (recursive search in a directory):

grep -qr "search-query" /path/to/dir && echo "FOUND" || echo "NOT FOUND"

CodePudding user response:

Why don't you base your script on this command:

grep -l "M1039C28" * | wc -l

If the result is 0, then the entry is not found.
If the result is 1 or more, the entry is found.

  • Related