From the command line, you can do:
ruby -i -pe '$_= "prepended text\n"+$_ if $. == 1' myfile
or more efficiently
ruby -i -pe 'BEGIN { gets; print "prepended text\n" + $_ }; ' myfile
Sadly, it turns out, the -i
(in-place) options isn't truly in-place, though (and nor is sed
s in-place option for that matter) -- my file will have a different inode after the op.
That made me sad, because effectively, I can't filter through (prepend to) a huge file if I don't have enough diskspace for two copies of it.
It's not really difficult to do it in-place, though (filtering in general, not just for the first line). All you need to do is:
1) make sure, you have separate read and write pointers (or separate File objects for reading and writing)
2) make sure you have buffered the unread parts that you are going to rewrite
3) truncate to file at the end if your filtering operation should end up with a shorter file
I wrote wrapper class for that at https://github.org/pjump/i_rewriter .
With it, you can do
Rewriter.new("myfile") do |line, index|
index == 0 ? "prepended text\n" + line : line
end
or with the executable:
$ i_rewriter 'index == 0 ? "prepended text\n" + line : line' myfile
Use carefully (it can corrupt your file if interrupted).