One liner to insert line in a file

Can someone help to come up with Ruby one-liner to add a line at the
beginning of a file? Basically a Ruby equivalent for following sed
example-
$ sed -i “1i $variable” file.txt

–neubyr

On Sat, Jan 7, 2012 at 3:07 PM, Neubyr N. [email protected] wrote:

Can someone help to come up with Ruby one-liner to add a line at the
beginning of a file? Basically a Ruby equivalent for following sed
example-
$ sed -i “1i $variable” file.txt

What have you tried so far?

Got it:
$ ruby -i -pe ‘print “First Line\n” if $.==1’ filename.txt

Thanks!

On Sat, Jan 7, 2012 at 10:28 PM, Josh C. [email protected]
wrote:

Downside is it doesn’t work on multiple files since Ruby’s $. doesn’t reset
for each file (not sure why not).

If you pass multiple files on the command line, they’re combined
through ARGF into one long stream.

Gavin

On Sat, Jan 7, 2012 at 1:34 AM, Neubyr N. [email protected] wrote:

Got it:
$ ruby -i -pe ‘print “First Line\n” if $.==1’ filename.txt

Thanks!


Posted via http://www.ruby-forum.com/.

Love this!

(btw, you can use puts instead of print "...\n")

Downside is it doesn’t work on multiple files since Ruby’s $. doesn’t
reset
for each file (not sure why not).

On Sat, Jan 7, 2012 at 5:32 AM, Gavin S. [email protected]
wrote:

Yeah, I guess it’s basically awk’s NR, but it seems like there should be
something equivalent to awk’s FNR

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs