Read more

Batch-process text files with ruby

Tobias Kraze
July 05, 2013Software engineer at makandra GmbH

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

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

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/*
Posted by Tobias Kraze to makandra dev (2013-07-05 15:37)