Bill Kelly
3/29/2005 9:08:00 PM
Hi,
From: "Ezra Zygmuntowicz" <ezra@yakima-herald.com>
>
> Can someone help out a n00b with a simple problem. What is the proper
> way to open all text files in a directory and the call gsub on each
> file? Thanks in advance.
This is something you can even do from the command line:
ruby -i~ -pe 'gsub(/foo/,"bar")' *.baz
The above should change foo to bar in all *.baz files, and
save the original files as *.baz~
Or, without using the command line:
files = Dir["*.txt"]
files.each do |filename|
content = File.read(filename) # note: File#read is ruby 1.8+
if content.gsub!(/foo/, "bar")
File.open(filename, "w") {|io| io.print content }
end
end
The above is untested, but should read each .txt file, perform
the gsub, and only write the file back if anything changed.
Hope this helps,
Regards,
Bill