Created
August 24, 2012 16:54
-
-
Save maxjustus/3452858 to your computer and use it in GitHub Desktop.
Global find and replace with optional confirm
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 | |
require 'rubygems' | |
require "highline/system_extensions" | |
include HighLine::SystemExtensions | |
orig, new, args = ARGV | |
args = Array(args) | |
file_names = Dir["**/*.*"] | |
file_names.each do |file_name| | |
text = File.read(file_name) | |
if text.index(orig) | |
p file_name | |
regexp = /(.*)(#{orig})(.*)/ | |
new_text = text.gsub(regexp) do |line| | |
number = $`.split("\n").count + 1 | |
puts "#{number}: #{line}" | |
replacement = if args.include?('-c') | |
print "Replace '#{orig}' with '#{new}'? (y/n): " | |
input = get_character.chr | |
puts | |
input == 'y' ? new : orig | |
else | |
new | |
end | |
line.gsub(orig, replacement) | |
end | |
File.open(file_name, "w") do |file| | |
file.puts new_text | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
gfr original replacement -c # comfirms each replacement
gfr original replacement # replaces without confirm