简体   繁体   English

如何在模式匹配目录Ruby中获取特定文件

[英]How to get the specific files in pattern-matching directory Ruby

I would like to write a Ruby script that would find if the directory from the same pattern then copy the folders and files inside to another directory. 我想编写一个Ruby脚本,该脚本将查找目录是否来自同一模式,然后将其中的文件夹和文件复制到另一个目录。

For example, if I want to find a pattern of directory that is: 例如,如果我想查找以下目录模式:

"./file/drive_Temp/**/tools/" “./file/drive_Temp/**/tools/”

it can be: 有可能:

  • ./file/drive_Temp/abc/tools/ ./file/drive_Temp/abc/tools/
  • ./file/drive_Temp/def/tools/ ./file/drive_Temp/def/tools/
  • ./file/drive_Temp/xyz/tools/ ./file/drive_Temp/xyz/tools/

as long as the front part starts with "./file/drive_Temp/" and end with "/tools/". 只要前面部分以“ ./file/drive_Temp/”开头并以“ / tools /”结尾。


what I want to do is to copy all the files that meet the pattern of the directory as mentioned to a new directory: 我要做的是将符合目录模式的所有文件复制到新目录中:

There might be some files in the following directory such as : 以下目录中可能有一些文件,例如:

  • ./file/drive_Temp/abc/tools/aaa.txt ./file/drive_Temp/abc/tools/aaa.txt
  • ./file/drive_Temp/abc/tools/bbb.txt ./file/drive_Temp/abc/tools/bbb.txt
  • ./file/drive_Temp/abc/tools/ccc.txt ./file/drive_Temp/abc/tools/ccc.txt
  • ./file/drive_Temp/def/tools/zzz.txt ./file/drive_Temp/def/tools/zzz.txt
  • ./file/drive_Temp/def/tools/yyy.txt ./file/drive_Temp/def/tools/yyy.txt
  • ./file/drive_Temp/def/tools/qqq.txt ./file/drive_Temp/def/tools/qqq.txt
  • ./file/drive_Temp/xyz/tools/ttt.txt ./file/drive_Temp/xyz/tools/ttt.txt
  • ./file/drive_Temp/xyz/tools/jjj.txt ./file/drive_Temp/xyz/tools/jjj.txt

those txt files would be move to directory called Tools 这些txt文件将移至名为Tools的目录

This is my code: 这是我的代码:

if File.directory?('./file/drive_Temp/**/tools')
    FileUtils.mv './file/drive_Temp/**/tools/*.*','./Tools'
end

Is the double asterisk not working? 双星号不起作用吗? Because the folder could not be moved to the directory specified. 因为无法将文件夹移动到指定的目录。 Or should I use glob instead? 还是应该改用glob

You could use Dir to get all the files within those directories, and iterate to move each of those files, like this: 您可以使用Dir来获取这些目录中的所有文件,并反复移动每个文件,如下所示:

Dir["./file/drive_Temp/**/tools/*"].each do |file|
  FileUtils.mv(file, './Tools')
end

Notice that this will replace any files that already exist in ./Tools ; 注意,这将替换 ./Tools中已经存在的所有文件; if such behavior needs to be avoided, then you can check if the file to be moved already exists in .Tools before moving it, for example: 如果需要避免这种行为,则可以在移动之前检查.Tools.Tools已存在要移动的文件,例如:

target_dir = "./Tools"

Dir["./file/drive_Temp/**/tools/*"].each do |file|
  if File.exist?("#{target_dir}/#{File.basename(file)}")
    # Handle file with duplicate name.
  else
    FileUtils.mv(file, target_dir)
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM