Modifying Files

Until now we’ve only dealt with using ARGF to read input. When we’re dealing with files, though, it’s common that we might also want to make modifications to them. With its in-place mode, Ruby offers a simple way to do this. This is useful if you’re running a filter across many different files—a find-and-replace task, for example.

We can invoke this mode by passing the -i flag to Ruby. For example, if we wanted to work across a set of files and change the spelling of a word across them all—the British tranquillity to the U.S. tranquility, for example—we could write the following simple script:

argf-sub.rb
 
ARGF.each ​do​ |line|
 
puts line.gsub(​"tranquillity"​, ​"tranquility"​)
 
end

We can run the script in the same way as ...

Get Text Processing with Ruby now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.