Batch-process text files with ruby

Posted Almost 11 years ago. Visible to the public.

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
Last edit
Almost 11 years ago
License
Source code in this card is licensed under the MIT License.
Posted by Tobias Kraze to makandra dev (2013-07-05 13:37)