Home > Mobile >  Copy folders which starts with character in Ruby
Copy folders which starts with character in Ruby

Time:10-22

How to copy folders which starts with only letters not with numbers. I am trying something like

  Dir.glob("folderpath/[a-z]").each do|f|
    FileUtils.cp_r f, "dest"
  end

CodePudding user response:

Dir glob expects to match the whole name (unlike regex).

So, you will need to do:

Dir.glob("folderpath/[a-z]*").each{|f|FileUtils.cp_r(f,"dest")}

(use the do syntax if you prefer)

see https://ruby-doc.org/core-3.0.0/Dir.html#method-c-glob

Note that if the underlying filesystem is case insensitive, then matching is made case insensitive although the pattern is lower case.

For instance, on a mac it matches README and etc

If you prefer regex, or need more complex test, you can use:

Dir.foreach("folderpath").
  select{|n|n.match(/^[a-z]/)}.
  map{|n|File.join("folderpath",n)}.
  each{|f|FileUtils.cp_r(f,"dest")}

Here we use a regex. Note it is case sensitive even if the underlying filesystem is case insensitive. Add i after the last / to make case insensitive if needed. The map is here to add the folder path so that you can add the cp_r

  • Related