我认为这是一个非常简单的问题,但我被困住了。
我正在尝试编写一个脚本来查看第一个目录,然后检查第二个目录以查看是否存在匹配的文件。如果文件匹配,我需要将文件从第二个目录复制到第三个目录,只要它们不存在于第三个目录中。
这是我到目前为止的副本。代码仍会覆盖第三个目录中的文件,即使它们已经存在。我做错了什么?
谢谢!
#!/usr/bin/ruby
require 'FileUtils'
library_path_1 = ARGV[0]
library_path_2 = ARGV[1]
library_path_3 = ARGV[2]
dir_1 = Dir.glob(library_path_1 + "/**/*").select{ |x| File.file? x }
dir_2 = Dir.glob(library_path_2 + "/**/*").select{ |x| File.file? x }
destination = Dir.glob(library_path_3 + "/**/*").select{ |x| File.file? x }
dir_1.each do |filename|
dir_2.each do |path|
destination.each do |existing_file|
existing_file = File.basename(existing_file)
if path.include?(File.basename(filename))
FileUtils.cp(path, library_path_3) unless File.exists?(existing_file)
end
end
end
end
答案 0 :(得分:1)
bn = dir1.map { |fn| File.basename fn } - destination.map { |fn| File.basename fn }
dir2.each { |fn| FileUtils.cp(fn, library_path_3) if bn.include? File.basename(fn) }
答案 1 :(得分:0)
您似乎正在通过其文件名验证文件,但您必须按全名检查它们,如下所示:
existing_file = File.basename(existing_file)
if path.include?(File.basename(filename))
FileUtils.cp(path, library_path_3) unless File.exist?(File.join(library_path_3, existing_file))
end
答案 2 :(得分:0)
dir_1.each do |file|
filename = File.basename(file)
if exists_in_dir2?(filename) && exists_in_dir3?(filename) == false
copy_to_destination(filename)
end
end
def copy_to_destination(filename)
File.copy(filename, "#{library_path_3}/{filename}")
end
def exists_in_dir2?(filename)
dir_2.each do |path|
path.include?("#{filename}")
end
end
def exists_in_dir3?(filename)
destination.each do |existing_file|
File.exist?("#{filename}")
end
end
答案 3 :(得分:0)
这是基于@Cary Swoveland答案的最终脚本。谢谢大家!
public class WebApplicationException extends Exception implements Serializable
{
private static final long serialVersionUID = 1L;
public WebApplicationException() {
super();
}
public WebApplicationException(String msg) {
super(msg);
}
public WebApplicationException(String msg, Exception e) {
super(msg, e);
}
}