Skip to content

Instantly share code, notes, and snippets.

@sbecker
Forked from maxjustus/gfr.rb
Created August 25, 2012 04:10
Show Gist options
  • Save sbecker/3460586 to your computer and use it in GitHub Desktop.
Save sbecker/3460586 to your computer and use it in GitHub Desktop.
Global find and replace with optional confirm (with colored diff)
#! /usr/bin/ruby
require 'rubygems'
require "highline/system_extensions"
require 'colorize'
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}".red
puts "+#{number}: #{line}".gsub(orig, new).green
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

sudo gem install highline colorize

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