Skip to content

Instantly share code, notes, and snippets.

@maxjustus
Created August 24, 2012 16:54
Show Gist options
  • Save maxjustus/3452858 to your computer and use it in GitHub Desktop.
Save maxjustus/3452858 to your computer and use it in GitHub Desktop.
Global find and replace with optional confirm
#! /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
@maxjustus
Copy link
Author

gfr original replacement -c # comfirms each replacement
gfr original replacement # replaces without confirm

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment