B
Ben
I've been trying to write a program that will take a file, do some
find/replace operation and save the file. I'm pretty new to ruby, and I
can't seem to figure out how to do this succinctly. This is my latest
attempt, but it seems like I shouldn't need to open the file twice.
I tried to just open the file with "r+" permissions, but if I overwrote
it with a string that was shorter than the original contents, the extra
characters would stick around. I couldn't figure out how to slice off
the extra stuff I didn't need.
Any suggestions on how to reduce this to one call to File.open???
Thanks! Any other suggestions are also appreciated. Here's the code...
print "pattern:"
pattern = STDIN.gets.chop
print "replacement:"
replacement = STDIN.gets.chop
str = ""
ARGV.each do |file|
File.open(file,"r+") do |handle|
str = handle.read
end
File.open(file,"w+") do |handle|
str.gsub!(/#{pattern}/,replacement)
handle.write(str)
end
end
Thanks,
Ben
find/replace operation and save the file. I'm pretty new to ruby, and I
can't seem to figure out how to do this succinctly. This is my latest
attempt, but it seems like I shouldn't need to open the file twice.
I tried to just open the file with "r+" permissions, but if I overwrote
it with a string that was shorter than the original contents, the extra
characters would stick around. I couldn't figure out how to slice off
the extra stuff I didn't need.
Any suggestions on how to reduce this to one call to File.open???
Thanks! Any other suggestions are also appreciated. Here's the code...
print "pattern:"
pattern = STDIN.gets.chop
print "replacement:"
replacement = STDIN.gets.chop
str = ""
ARGV.each do |file|
File.open(file,"r+") do |handle|
str = handle.read
end
File.open(file,"w+") do |handle|
str.gsub!(/#{pattern}/,replacement)
handle.write(str)
end
end
Thanks,
Ben