Skip to content

Instantly share code, notes, and snippets.

@ismaels
Last active February 3, 2018 17:45
Show Gist options
  • Save ismaels/a64e1c9b623d46256758 to your computer and use it in GitHub Desktop.
Save ismaels/a64e1c9b623d46256758 to your computer and use it in GitHub Desktop.
Compare the contents of two folders
#!/usr/bin/env ruby
# encoding: utf-8
require 'fileutils'
errors = []
folderA = 'folder1'
folderB = 'folder2'
# list all files in each folder
filesFolderA = Dir["./#{folderA}/*.txt"]
filesFolderB = Dir["./#{folderB}/*.txt"]
if filesFolderA.size != filesFolderB.size
errors << "Number of files in folders is different. A: #{filesFolderA.size} files, B: #{filesFolderB.size} files."
end
filesFolderA.sort!
filesFolderB.sort!
# create a list of filenames
namesA = filesFolderA.map do |a|
a.gsub("./#{folderA}/",'')
end
namesB = filesFolderB.map do |b|
b.gsub("./#{folderB}/",'')
end
# find the missing files in folder A
missingFilesA = namesB - namesA
if missingFilesA.size > 0
errors << "Missing files on folder '#{folderA}': #{missingFilesA.join(', ')}"
end
# find missing files in folder B
missingFilesB = namesA - namesB
if missingFilesB.size > 0
errors << "Missing files on folder '#{folderB}': #{missingFilesB.join(', ')}"
end
# compare files
maxItems = [filesFolderA.size, filesFolderB.size].max
first = filesFolderA
second = filesFolderB
if filesFolderB.size == maxItems
first = filesFolderB
second = filesFolderA
end
first.zip(second) do |pair|
if not pair.first.nil? and not pair.last.nil?
if not FileUtils.compare_file(pair.first.to_s, pair.last.to_s)
errors << "\"#{pair.first}\" is different from \"#{pair.last}\""
end
end
end
puts "=" * 20
puts errors
puts "=" * 20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment