Torstein Torstein - 7 months ago 19
Perl Question

Ruby equivalent of Perls one line string replacer

With perl, you can do this:

$ perl -pi -e 's/foo/bar/g' *.txt

Which will replace the string "foo" with "bar" on all *.txt files in the current directory.

I like this, but I was wondering if the same thing is possible using Ruby.


Yep. Ruby has an equivalent for most of Perl's command line options, and many of them are identical.

$ ruby -pi -e 'gsub /foo/, "bar"' *.txt

Here are the relevant docs from man ruby:

  • -i extension – Specifies in-place-edit mode. The extension, if specified, is added to old file name to make a backup copy. For example:

    % echo matz > /tmp/junk
    % cat /tmp/junk
    % ruby -p -i.bak -e '$_.upcase!' /tmp/junk
    % cat /tmp/junk
    % cat /tmp/junk.bak
  • -n – Causes Ruby to assume the following loop around your script, which makes it iterate over file name arguments somewhat like sed -n or awk.

    while gets
  • -p – Acts mostly same as -n switch, but print the value of variable $_ at the each end of the loop. For example:

    % echo matz | ruby -p -e '$! "a-z", "A-Z"'

My code above uses Kernel#gsub, which is only available in -p/-n mode. Per the docs:

gsub(pattern, replacement) → $_
gsub(pattern) {|...| block } → $_

Equivalent to $_.gsub..., except that $_ will be updated if substitution occurs. Available only when -p/-n command line option specified.

There are a handful of other such Kernel methods, which are useful to know: chomp, chop, and (naturally) sub.

Check out man ruby; there are a lot of great features.