G0elAyush
G0elAyush

Reputation: 53

How to check whether any file in the directory has a given string

Folder_name = "D:\newfolder\xxx"
echo "enter keyword"
read string
if grep $string $Folder_name;
then
  echo "yes"
else
  echi "no"
fi

Upvotes: 1

Views: 166

Answers (5)

Umar Ahmad
Umar Ahmad

Reputation: 410

You can use this to search

  cd "$Folder_name" && count=$(grep -R -c "$string")
  if [ $count -gt 0 ]; then
      echo "Yes"
  else
      echo "No"
  fi

This would recursively search for all files in the folder.

Upvotes: 1

David W.
David W.

Reputation: 107090

Are you looking for a file that contains a particular string, or are you looking for a file name that contains a particular string?

File that contains a string:

find . -type f -exec grep -l "string" {} \;

File name that contains a particular string:

find . -type f | grep "string"

Upvotes: 1

glenn jackman
glenn jackman

Reputation: 247250

I would say

found=false
for file in *; do
    if grep -q "$string" "$file"; then
        found=true
        break
    fi
done
if $found; then
    echo "at least one file contains $string"
else
    echo "no files contain $string"
fi

Upvotes: 1

Carlos Acedo
Carlos Acedo

Reputation: 11

If you are looking for a Yes/No response, you can use this one line command:

grep -q $string $Folder_name/* && echo 'Yes'|| echo 'No'

Upvotes: 1

Barmar
Barmar

Reputation: 782785

Use this:

Folder_name=/newfolder/xxx
echo "enter keyword"
read string
if grep -q -F "$string" "$Folder_name"/*
then echo yes
else echo no
fi
  1. There are no spaces around = in shell variable assignments.
  2. grep requires filename arguments, not directories, unless you use the -r option to search the directory recursively.
  3. The -q option tells grep not to print the matching lines.
  4. The -F option tells it to treat $string as a verbatim string rather than a regular expression.
  5. You should quote variables in case they contain whitespace or wildcard characters.

Upvotes: 1

Related Questions