开发者

Fastest way to find text in folder

开发者 https://www.devze.com 2022-12-14 22:07 出处:网络
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

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

精彩评论

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