So I’ve been fiddling with Rio recently. I’m trying to write a little script to find and replace throughout a directory – and all its subdirectories, recursively. Given the end result of this might end up being an application based upon Rails, it seemed best to write this in Ruby. And I remembered someone (Tiest, I think) mentioning Rio at one of the LRUG meetings. So I gave it a shot.
Rio is, in short, lovely. It acts as a convenience wrapper around a whole host of modules – including Kernel
, File
, Dir
, and others – and basically makes reading and writing files a doddle. It’s also quite powerful, and makes batch operations across directories really easy, once you’ve figured it out.
So my global find/replace script comes down to this:
rio('dirname').all.files.skip(/^\./).do |eachfile|
eachfile < eachfile.contents.gsub("search", "replace")
end
And that's it. Obviously, this being gsub
, "search
" can be replaced with any regular expression of your choosing. I'm sure I could do it faster in sed/awk/grep, but I'm not as familiar with them as many - and this way around, I can patch this snippet into a larger Ruby application. The skip
clause forces Rio to ignore files beginning with a dot, as .DS_Store
and friends cause it problems (it seems).
Anyhow, I'm very impressed with Rio - saves a lot of faffing with read and write modes - and can highly recommend it if you need to faff with the file system in Ruby.