2011-05-17

Ruby : 10MB 이상의 파일중에서 중복된 파일 찾기

아래 코드에서 파일에 대한 MD5SUM 을 구하기 위해서 주석 처리한 부분을 대신 사용할 수 도 있다. 인터넷에서 찾아보면 이렇게 되어 있는 경우가 많은데, 이렇게 하면 메모리를 많이 잡아먹는 문제가 발생한다. 반드시 Digest::MD5.file().hexdigest 를 이용해야만 적은 메모리를 사용하면서 원활하게 동작되니 주의하기 바란다.

10MB 이상의 파일중에서 중복된 파일 찾기
# -*- coding: cp949 -*-
require 'find'
require 'digest/md5'
 
file_list = Array.new
Find.find("C:\\") do |path|
  if File.file?(path) and File.size(path) > 10_000_000
    # digest = Digest::MD5.hexdigest(File.read(path))
    # --> 위와 같이 해도 되지만, 메모리를 많이 잡아먹는다.
    digest = Digest::MD5.file(path).hexdigest
    file_list << digest+"|"+path
  end
end
 
distinct_list = Hash.new(0)
file_list.each do |val|
  (md5, file) = val.split(/\|/)
  distinct_list[md5] += 1
end
 
distinct_list.each do |md5, count|
  if count >= 2
    print "\n["+md5+"]\n"
    file_list.each do |val|
      (md5_2, file) = val.split(/\|/)
      if md5 == md5_2
        print file+"\n"
      end
    end
  end
end


댓글 없음:

댓글 쓰기