Stan
Stan

Reputation: 3461

find multiple patterns in multiple files bash

I'm trying to find multiple patterns (I have a file of them) in multiple differents files with a lot of subdirs. I'm trying to use exit codes for not outputting all patterns found (because I need only the ones which are NOT found), but exit codes doesn't work as I understand them.

while read pattern; do
  grep -q -n -r $pattern ./dir/
  if [ $? -eq 0 ]; then
    : #echo $pattern ' exists'
  else
    echo $pattern " doesn't exist"
  fi
done <strings.tmp

Upvotes: 2

Views: 467

Answers (2)

anubhava
anubhava

Reputation: 785186

You can use this in bash:

while read -r pattern; do
  grep -F -q -r "$pattern" ./dir/ || echo $pattern " doesn't exist"
done < strings.tmp
  • Use read -r to safely read regex patterns
  • Use quoting in "$pattern" to avoid shell escaping
  • No need to use -n since you're using -q (quiet) flag

Upvotes: 2

Ponmani Palanisamy
Ponmani Palanisamy

Reputation: 78

@anubhava's solution should work. If it doesn't for some reason, try the following

while read -r pattern; do
 lines=`grep -q -r "$pattern" ./dir/ | wc -l`
 if [ $lines -eq 0 ]; then
    echo $pattern " doesn't exist"
 else
    echo $pattern "exists"
 fi
done < strings.tmp

Upvotes: 1

Related Questions