Find/Replace across a project
2006/11/03 00:59:26 +0000
Jim Weirich introduced using Rake as a library with his Find in Code
I’ve been enjoying fic, which lives in my ~/bin directory at work. Enjoying it so much that I decided I needed something as powerful for replacing in code. This small variant on Find in Code saved me much time in renaming a couple of models this afternoon.
Replace in Code
#!/usr/bin/env ruby
# -*- ruby -*-
require 'rubygems'
require 'breakpoint'
exts = ['.rb']
if ARGV[0] =~ /^\.[a-zA-Z0-9]+$/
exts = []
while ARGV[0] =~ /^\.[a-zA-Z0-9]+$/
exts << ARGV.shift
end
end
ext = "{" + exts.join(',') + "}"
if ARGV.size < 1
puts "Usage: #{File.basename($0)} [.ext ...] pattern replacement"
exit 1
end
pattern = Regexp.new(ARGV.first)
replace = ARGV.last
require 'rubygems'
require 'rake'
FileList["**/*#{ext}"].egrep(pattern) do |fn, ln, line|
string = File.open(fn).read
st_array = string.split("\n")
st_array[ln-1].gsub!(pattern, replace)
new_string = st_array.join("\n")
File.open(fn, 'w') do |f|
f.write new_string
end
puts "#{fn}:#{ln} replaced: \nold: #{line}new: #{line.gsub(pattern, replace)}"
end
Thanks, Jim!