From: Bill Kelly Date: 2005-03-30T06:08:12+09:00 Subject: Re: open files in a dir then gsub all of them? Hi, From: "Ezra Zygmuntowicz" > > 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