Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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?

like image 755
synek317 Avatar asked Jan 16 '17 14:01

synek317


Video Answer


1 Answers

Ruby-only

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.

Bash-only

For a bash-only solution, you could use :

  • compgen
  • Shell find
like image 59
Eric Duminil Avatar answered Oct 21 '22 10:10

Eric Duminil