Created
April 11, 2009 13:15
-
-
Save vitaliel/93564 to your computer and use it in GitHub Desktop.
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
# replace string in files recursively. | |
# author: Vitalie Lazu | |
s = ARGV[0] | |
r = ARGV[1] | |
FILES = /\.(rb|erb|rhtml|rake|yml|rjs|rxml)$/ | |
def suggest_bak(file) | |
bak = "#{file}~" | |
i = 1 | |
loop do | |
break unless test ?f, bak | |
bak = "#{file}~#{i}" | |
i += 1 | |
end | |
bak | |
end | |
def replace_content(type, str, search, replace) | |
if type == :line | |
changed_lines = 0 | |
rez = [] | |
str.each_line do |l| | |
rez << l | |
changed_lines += 1 if l.gsub!(search, replace) | |
end | |
if changed_lines > 0 | |
str.replace rez.join | |
end | |
return changed_lines | |
else | |
return 1 if str.gsub!(search, replace) | |
end | |
0 | |
end | |
def replace(search, replace) | |
Dir.foreach('.') do |d| | |
next if d =~ /^\.+$/ | |
if test ?d, d | |
Dir.chdir d | |
replace(search, replace) | |
Dir.chdir ".." | |
end | |
next if d !~ FILES | |
bak = suggest_bak(d) | |
size = -1 | |
File.open(d, "r+") do |f| | |
str = f.read | |
bak_str = str.clone | |
if replace_content(:line, str, search, replace) > 0 | |
f.rewind | |
File.open(bak, "w") do |g| | |
g.write bak_str | |
end | |
str << "\n" if str.length > 0 && str[-1] != 10 | |
f.write(str) | |
size = str.length | |
end | |
end | |
File.truncate(d, size) if size >= 0 | |
end | |
end | |
if s.nil? || r.nil? | |
puts "provide search and replace params" | |
else | |
puts "'#{s}', '#{r}'" | |
replace(s, r) | |
#replace(/^[ \t\r]+$/, '') | |
#replace(/[ \t\r]+$/, '') | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment