Last active
December 16, 2015 23:59
-
-
Save ifukazoo/5517870 to your computer and use it in GitHub Desktop.
ファイル内の文字列を一括置換する.
This file contains 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/ruby -w | |
# encoding: utf-8 | |
require 'optparse' | |
require 'fileutils' | |
bak = from = to = nil | |
#引数解析 | |
opt = OptionParser.new | |
opt.on("-b", "--backup <extention>", String) {|val| bak = val} | |
opt.on("-f", "--from <from>" , Regexp) {|val| from = val} | |
opt.on("-t", "--to <to>" , String) {|val| to = val} | |
begin | |
opt.parse!(ARGV) | |
rescue | |
print opt.to_s | |
exit | |
end | |
raise opt.to_s if bak.nil? or from.nil? or to.nil? | |
ARGV.each do |filename| | |
backup = filename + bak | |
lines = open(filename, "r+").readlines | |
replaced_lines = lines.map {|line| line.gsub(from,to) } | |
next if replaced_lines.eql? lines | |
begin | |
FileUtils.cp(filename, backup) | |
f = open(filename, "w") | |
replaced_lines.each {|line| f.write(line)} | |
rescue | |
FileUtils.rm(filename) | |
FileUtils.mv(backup, filename) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment