Last active
December 25, 2015 08:48
-
-
Save ssut/6948983 to your computer and use it in GitHub Desktop.
Simple ruby script: find string in multiple files and replace.
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/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