Hey there list-
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.
-Ezra Zygmuntowicz
Yakima Herald-Republic
WebMaster
509-577-7732
ezra@yakima-herald.com
Hi,
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
···
From: "Ezra Zygmuntowicz" <ezra@yakima-herald.com>