Batch-process text files with ruby

Did you know you can do in-place batch processing with plain ruby?

The following script will in-place replace "foo" with "bar" in all files you feed it. Call it with ./my_script path/to/my/files/*

#!ruby -i -p
$_.gsub!(/foo/, "bar")

"'-i -p" means:

Ruby will run your script once for each line in each file. The line will be placed in $_. The value of $_ at the end of your script will be written back to the file.

Shorter

Using the Kernel#gsub shorthand for $_.gsub!:

#!ruby -i -p
gsub(/foo/, "bar")

Still shorter

Pass the whole script on the command line

  ruby -i -p -e 'gsub(/foo/, "bar")' path/to/my/files/*
Tobias Kraze Almost 11 years ago