On Fri, Jan 11, 2013 at 12:07 PM, Arup Rakshit <lists / ruby-forum.com> wrote:
> Bartosz Dziewoski wrote in post #1091898:
>> On Fri, 11 Jan 2013 13:03:28 +0100, Arup Rakshit <lists / ruby-forum.com>
>> wrote:
>
>>> -F pat
>>>
>>> -i [ ext]
>>
>
> Can any one help me to understand how the above two options work in
> Ruby?

They are all used primarily for one-liners (i.e. invocations where a
script is specified as a string on the command line after -e); the
switches in question closely mirror those present in perl, awk, and
sed.

-F is for use only with -a; -a in turn is for use only with -n or -p.

-n and -p take the script that's the argument to -e and wrap it in a
loop. The loop is equivalent to `while gets; <SCRIPT> end`; the `gets`
puts the line read into the variable $_. The difference between the
two is that -p prints each line read, while -n doesn't. (Throught
experimentation, I just found out $_ gets printed at the *end* of each
loop iteration; so if you modify $_ inside the loop, it will print the
modified version.)

-a causes Ruby to automatically split each line read into $_; the
result goes into $F, an array.

-F lets you specify the separator to be used by -a.

Thus, if we have a file foo:
foo:bar:foo

and we use the command line:
$ ruby -a -F: -n -e 'p $F' foo

we get the output:
["foo", "bar", "foo\n"]

Now, -i is used to make changes to files supplied on the command line,
without having to code that specifically in the script. The argument
to -i specifies a filename extension to append to the filename(s), to
back up the old file(s). Thus if we have the above file foo and
another file named bar, with the contents:
bar:foo:bar

and we use the command line:
$ ruby -i~ -p -e "$_.gsub!(/bar/, 'baz')" foo bar

we will end up with these files:
foo~:
foo:bar:foo

bar~:
bar:foo:bar

foo:
foo:baz:foo

bar:
baz:foo:baz

`ruby -h` (at least in 1.9.3) implies that you can use -i without an
extension, in which case no backup will be made; but I can't get it to
accept -i without an extension at the moment:

$ ruby -i -p -e "$_.gsub!(/bar/, 'baz')" foo bar
-e:1:in `gets': Can't do inplace edit without backup (fatal)
        from -e:1:in `gets'
        from -e:1:in `<main>'

Obviously though it's a good idea to keep a backup.