Created
April 25, 2016 05:32
-
-
Save gunyarakun/469e1aadad753ac82004fee218b1ab4c to your computer and use it in GitHub Desktop.
ディレクトリ・ファイル名とファイルの中身のテキストを置換する
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# encoding: utf-8 | |
# ディレクトリ・ファイル名とファイルの中身のテキストを置換する | |
require 'fileutils' | |
require 'open3' | |
PATTERN = 'AF' | |
REPLACEMENT = 'TomboAF' | |
DRY_RUN = false | |
def move(base_path, file_name) | |
path = File.join(base_path, file_name) | |
if File.directory?(path) | |
recursive_move(path) | |
end | |
new_path = File.join(base_path, file_name.gsub(PATTERN, REPLACEMENT)) | |
if path != new_path | |
if DRY_RUN | |
puts "#{path} -> #{new_path}" | |
replaced_path = path | |
else | |
FileUtils.mv path, new_path | |
replaced_path = new_path | |
end | |
else | |
replaced_path = path | |
end | |
if text_file?(replaced_path) | |
text = File.read(replaced_path) | |
new_text = text.gsub(PATTERN, REPLACEMENT) | |
if text != new_text | |
if DRY_RUN | |
puts "Replace #{PATTERN} in #{replaced_path}" | |
else | |
File.open(replaced_path, 'w') {|f| f.write new_text } | |
end | |
end | |
end | |
end | |
def text_file?(path) | |
file_type, status = Open3.capture2e('file', path) | |
status.success? && file_type.include?('text') | |
end | |
def recursive_move(base_path) | |
Dir.foreach(base_path) do |file_name| | |
next if file_name == '.' || file_name == '..' | |
move(base_path, file_name) | |
end | |
end | |
if ARGV.length != 1 | |
puts 'Usage: mv.rb directory' | |
exit | |
end | |
recursive_move(ARGV[0]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment