MAXGEN
MAXGEN

Reputation: 755

Bash grep avoid checking directories

I'm getting errors because I search through sub directories and I don't want it to search those just the files that are in this folder. The other folders are LOGS and RESULTS and contain other files. How do you stop to just search the files in Downloads?

is_file_contains_VAR()
{
grep -q -e "$VAR" "$1"

}

for f in *
do
   if [ -f "$f" ]; then
      if is_file_contains_VAR"$f"; then
    echo "FILE exist in " $f

    #echo "Processing $f file..."

        # take action on each file. $f store current file name
    #cat $f
    else
        echo "echo "FILE DOES NOT exist in " $f
     fi

 done

Upvotes: 2

Views: 96

Answers (3)

anubhava
anubhava

Reputation: 785146

You can do:

cd Downloads/
for f in *
do
   [[ -f "$f" ]] && is_file_contains_VAR "$f" && echo "found"
done

EDIT:

for f in *
do
   if [ -f "$f" ]; then
      if is_file_contains_VAR "$f"; then
          echo "FILE exist in $f"
      else
          echo "echo "PATTERN DOES NOT exist in $f"
      fi
   fi
done

Upvotes: 1

glenn jackman
glenn jackman

Reputation: 246807

You could use find instead of the general * to iterate over specifically files:

find . -maxdepth 1 -type f -print0 |
while read -d '' -r file; do
    do_something_with "$file"
done

-maxdepth 1 stops find from descending into subdirectories.

I assume GNU find.

Always quote your "$variables" unless you specifcally know when to not quote them.

Upvotes: 2

Alfe
Alfe

Reputation: 59426

Add a

[ -d "$f" ] && continue

at the beginning of your loop. If $f is a directory, it will get skipped.

Btw, you might consider what device files, fifos and symbolic links should result in. Maybe you want to use [ -f "$f" ] || continue to only check regular files (and symbolic links to regular files).

Upvotes: 4

Related Questions