Mark Hubbart
1/17/2005 7:58:00 AM
On Mon, 17 Jan 2005 14:11:07 +0900, Ben <bhbrinckerhoff@wustl.edu> wrote:
> 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)
handle.truncate(handle.pos)
> end
> end
File#truncate(size) truncates the file to the given size. Passing your
current position after you write to the file truncates it immediately
after the last character you wrote.
HTH,
Mark