Sehaj Paul Singh
Sehaj Paul Singh

Reputation: 55

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

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

Upvotes: 1

Views: 176

Answers (3)

lacostenycoder
lacostenycoder

Reputation: 11186

If you have a large directory and want to search recursively, try using the silver searcher if not already installed, you can with on Debian sudo apt install silversearcher-ag or brew install the_silver_searcher on MacOS. Use it like this.

ag "M1039C28" path/to/search && echo "FOUND" || echo "NOT FOUND"

note path argument is optional, by default it searches current path recursively.

Upvotes: 1

user10304260
user10304260

Reputation:

Consider using grep with options -q (suppress any output) and -r (recursive search in a directory):

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

grep will exit with code 1 if it could not find the string in any files. For more information, see the man page

Upvotes: 6

Dominique
Dominique

Reputation: 17493

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.

Upvotes: 1

Related Questions