views:

169

answers:

3

I was using the return value of fgrep -s 'text' /folder/*.txt to find if 'text' is in any .txt file in /folder/. It works, but I find it too slow for what I need, like if it searches for 'text' in all the files before giving me an answer.

I need something that quickly gives me a yes/no answer when it finds at least one file with the 'text'. Probably some awk script.

+5  A: 

If I understand your question correctly, you want:

fgrep -m1

Which stops after one match.

mopoke
Just tried it and it doesn't work. Illegal option. I'm using it on a Solaris machine.
lamcro
+1  A: 

You can use this to shorten your search if it's the kind that would be based on mopoke's answer. This stops after the first match in the first file in which it's found:

# found=$(false)
found=1    # false
text="text"
for file in /folder/*.txt
do
    if fgrep -m1 "$text" "$file" > /dev/null
    then
        found=$?
        # echo "$text found in $file"
        break
    fi
done
# if [[ ! $found ]]
# then
#    echo "$text not found"
# fi
echo $found # or use exit $found

Edit: commented out some lines and made a couple of other changes.

If there is a large number of files, then the for could fail and you should use a while loop with a find piped into it.

If all you want to do is find out whether there is any .txt file in a folder regardless of the file's contents, then use something like this all by itself:

find /folder -name "*.txt"
Dennis Williamson
I would like to try your's, without de `-m1`, but I need it to return 1 if there is a match and 0 if not. Not as an echo printout, but as a command's return value. Thanks!
lamcro
Sorry for asking, but scripting language is this? I'm guessing Bash.
lamcro
Yes, it's Bash, but something similar could be done with other shells. What shell do you use? Normally, 0 is true and 1 is false. Try this in Bash: `true; echo $?; false; echo $?` - you should get a zero then a one. See my edit above to show how to make use of this.
Dennis Williamson
A: 

Building on the answers above, this should do it I think ?

find /folder -name \*.txt -exec grep "text" {}\;

But I'm not sure I fully understand the problem : is 'fgrep' doing a full depth recursion before it starts outputting or something ? The find should report as-it-finds so might be better for what you need, dunno.

[edit, not tested]: Change the 'grep' above for a shell-script that does something like:

grep "text" && exit 0 || exit 1

To get the true|false thing you need to work (you'll need to play around with this , haven't tested exactly the steps here - no access to Unix at the moment :-( )

monojohnny