使用 Ruby 将文件从一个目录复制到另一个目录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9519645/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 04:50:51  来源:igfitidea点击:

Copying a file from one directory to another with Ruby

rubydir

提问by 1dolinski

Hey I'm trying to move multiple files from one folder to another. In the FileUtils line I am trying to search through all of the 4 character folders in the destination folder and then paste the file in the folder with the same base name as the file.

嘿,我正在尝试将多个文件从一个文件夹移动到另一个文件夹。在 FileUtils 行中,我试图搜索目标文件夹中的所有 4 个字符文件夹,然后将文件粘贴到与文件具有相同基本名称的文件夹中。

#!/usr/bin/env ruby

require 'fileutils'

my_dir = Dir["C:/Documents and Settings/user/Desktop/originalfiles/*.doc"]
my_dir.each do |filename| 
  FileUtils.cp(filename, "C:/Documents and Settings/user/Desktop/destinationfolder/****/" + File.basename(filename, ".doc"))
end

回答by David Grayson

Something like this should work.

像这样的事情应该有效。

my_dir = Dir["C:/Documents and Settings/user/Desktop/originalfiles/*.doc"]
my_dir.each do |filename|
  name = File.basename('filename', '.doc')[0,4]
  dest_folder = "C:/Documents and Settings/user/Desktop/destinationfolder/#{name}/"
  FileUtils.cp(filename, dest_folder)
end

You have to actually specify the destination folder, I don't think you can use wildcards.

您必须实际指定目标文件夹,我认为您不能使用通配符。

回答by the Tin Man

*is a wildcard meaning "any number of characters", so "****" means "any number of any number of any number of any number of characters", which is probably not what you mean.

*是一个通配符,意思是“任意数量的字符”,所以“ ****”的意思是“任意数量的任意数量的任意数量的任意数量的字符”,这可能不是你的意思。

?is the proper symbol for "any character in this position", so "????" means "a string of four characters only".

?是“此位置的任何字符”的正确符号,因此“ ????”表示“仅包含四个字符的字符串”。

回答by Gabriel Guérin

I had to copy 1 in every 3 files from multiple directories to another. For those who wonder, this is how I did it:

我不得不将每 3 个文件中的 1 个从多个目录复制到另一个目录。对于那些想知道的人,我是这样做的:

# frozen_string_literal: true

require 'fileutils'

# Print origin folder question

puts 'Please select origin folder'

# Select origin folder

origin_folder = gets.chomp

# Select every file inside origin folder with .png extension

origin_folder = Dir["#{origin_folder}/*png"]

# Print destination folder question

puts 'Please select destination folder'

# Select destination folder

destination_folder = gets.chomp

# Select 1 every 3 files in origin folder
(0..origin_folder.length).step(3).each do |index|
  # Copy files
  FileUtils.cp(origin_folder[index], destination_folder)
end