Check if there is any file or directory matching the pattern using ruby

I want to check a wildcard pattern, for example. /var/data/**/*.xmlmatches any file or directory on the disk.

Obviously, I could use it Dir.glob, but it is very slow when there are millions of files, because it is too impatient - it returns all the files that match the template, while I only need to know if there are any.

Is there any way to check this?

+4
source share
1 answer

ruby only

You can use Find, Findand Find: D.

I could not find another 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 want to have a boolean:

require 'find'
Find.find("/var/data/").any?{|f| f=~/\.xml$/i }

, "/var/data/" , .xml, , Dir.glob.

:

Dir.glob("/var/data/**/*.xml"){|f| break f}

.

Bash -

bash -only :

+3

Source: https://habr.com/ru/post/1666917/


All Articles