2

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 
1
  • It would be useful to show a sample of your file strings.tmp. Are you trying to match regular expression patterns or fixed strings? How exactly is the code not working? Please edit your question to provide these details. Commented Nov 26, 2014 at 11:16

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

4 Comments

yeah, thx, command works by itself, but doesn't work in cycle. I mean it's ok when I take non-exist pattern and check it, but checking it in a loop doesn't work..
There is no reason for it to not work in loop. Show content of strings.tmp in question.
test.hello test2.world and similar strings on each line
ok, i found, the problem was in dots in strings, which are interpreted as a special regexp symbol. just added -F flag for this
1

@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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.