开发者

Fastest way to find text in folder

I was using the return value of fgrep -s 'text' /folder/*.txt to find if 'text' is in any .txt file in /folder/. 开发者_Go百科 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.


If I understand your question correctly, you want:

fgrep -m1

Which stops after one match.


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"


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 :-( )

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜