Skip to content

Instantly share code, notes, and snippets.

@ssut
Last active December 25, 2015 08:48
Show Gist options
  • Save ssut/6948983 to your computer and use it in GitHub Desktop.
Save ssut/6948983 to your computer and use it in GitHub Desktop.
Simple ruby script: find string in multiple files and replace.
#!/usr/bin/env ruby
#
# First: Filename (*.html, *.rb, *.py and etc)
# Second: Find
# Third: Replacement
$pwd = Dir.pwd
$args = []
ARGV.each { |arg| $args.push(arg) }
if $args.size < 3
puts "Need three arguments."
exit
end
files = Dir.glob File.join($pwd, "**/", $args[0])
find = Regexp.new $args[1]
repl = $args[2]
files.each do |file|
str = ""
open(file) { |fp| str = fp.read }
if str.include?($args[1])
print "Found '#{file.sub($pwd, "")}'\n"
open(file, "w") do |fp|
fp.write str.gsub(find, repl)
print " - Replace complete\n"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment