I want to check if pattern with wildcards, e.g. /var/data/**/*.xml
is matching to any file or directory on the disk.
Obviously I could use Dir.glob
but it is very slow when there are millions of files because it is too eager - it returns all files matching the pattern while I only need to know if there is any.
Is there any way I could check that?
You could use Find
, find
and find
:D.
I couldn't find any other File/Dir method that returns an Enumerator.
require 'find'
Find.find("/var/data/").find{|f| f=~/\.xml$/i }
#=> first xml file found inside "/var/data". nil otherwise
# or
Find.find("/var/data/").find{|f| File.extname(f).downcase == ".xml" }
If you really just want a boolean :
require 'find'
Find.find("/var/data/").any?{|f| f=~/\.xml$/i }
Note that if "/var/data/"
exists but there is no .xml
file inside it, this method will be at least as slow as Dir.glob
.
As far as I can tell :
Dir.glob("/var/data/**/*.xml"){|f| break f}
creates a complete array first before returning its first element.
For a bash-only solution, you could use :
compgen
find
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With