Skip to content

Instantly share code, notes, and snippets.

@jacoyutorius
Last active December 1, 2020 13:59
Show Gist options
  • Select an option

  • Save jacoyutorius/d907ab73120215db0d7c1aa6823ca53d to your computer and use it in GitHub Desktop.

Select an option

Save jacoyutorius/d907ab73120215db0d7c1aa6823ca53d to your computer and use it in GitHub Desktop.
連番が振られた同じファイルを抽出するRubyスクリプト
require 'fileutils'
class DuplicateFileCleaner
class << self
def run(dir: '', extname: 'txt', dryrun: false)
self.new(extname, dryrun).cleanup(dir)
end
end
def initialize(extname, dryrun)
@extname = extname
@dryrun = dryrun
end
def cleanup(dir)
p "------#{ dir }------"
# ファイル名の重複しているファイルを抽出してゴミ箱へ
files = Dir.glob(dir + '/*.' + @extname).filter {|v| !File.directory?(v) }
go_to_trash(dir, files) if files.length > 0
# 下の階層を検索
dirs = Dir.glob(dir + '/**').filter {|v| File.directory?(v) }
dirs.each {|dir| cleanup(dir) } if dirs.length > 0
end
private
def dig_targets(file_names)
file_names.map do |f|
regexp = Regexp.new(/^#{f}\s\d+$/)
file_names.select{|f| f.match(regexp) }
end.uniq.flatten
end
def move_to_dir(from)
ar = from.split("/")
ar.shift
ar.join('/')
end
def go_to_trash(dir, files)
file_names = files.map{|f| File.basename(f, '.' + @extname) }
target_files = dig_targets(file_names) if file_names.length > 0
# ゴミ箱ディレクトリを作ってそこに移動させる
FileUtils.mkdir_p("trashbox/#{dir}") unless @dryrun
target_files.each do |name|
pp [
"#{dir}/#{name}.#{@extname}",
"./trashbox/#{move_to_dir(dir)}/#{name}.#{@extname}"
]
unless @dryrun
FileUtils.mv(
"#{dir}/#{name}.#{@extname}",
"./trashbox/#{move_to_dir(dir)}/#{name}.#{@extname}"
)
end
end
end
end
DuplicateFileCleaner.run(dir: './root', extname: 'mp3', dryrun: true)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment