star7 has asked for the wisdom of the Perl Monks concerning the following question:

Hi,
do you know the command for insertion of a line in a textfile ?
I want insert a line in a textfile. the new line is the first line in the new textfile.
Thanks for your help.
star7

Replies are listed 'Best First'.
Re: need help:insert a line in a textfile
by jmcnamara (Monsignor) on Sep 11, 2003 at 13:19 UTC

    As a one-liner (with backup), see perlrun:
    perl -i.bak -pe 'print "New line here\n" if $. == 1' file

    --
    John.

Re: need help:insert a line in a textfile
by broquaint (Abbot) on Sep 11, 2003 at 13:14 UTC
    That's just a simple perl one-liner e.g
    perl -pi -e '$. == 1 and print $/' textfile
    See. perlrun and perlvar for more info.
    HTH

    _________
    broquaint

Re: need help:insert a line in a textfile
by Zaxo (Archbishop) on Sep 11, 2003 at 13:23 UTC

    There is not a single command to insert a line into a file. The Tie::File module gives a convenient way to do it.

    use Tie::File; my $newline = "whatever"; { tie my @array, 'Tie::File', '/path/to/file.txt'; unshift @array, $newline; }
    If you wish to insert a line elsewhere, splice works with that.

    After Compline,
    Zaxo

Re: need help:insert a line in a textfile
by Abigail-II (Bishop) on Sep 11, 2003 at 13:26 UTC
    And an alternative for a test on $. for each line of the file:
    $ perl -pwle 'BEGIN {print "First Line!"}' your_file

    Or even

    $ perl -Mstrict='}, print +("First Line"), qw {' -pwle1 your_file

    Abigail


      Not testing $. is more efficient but it is worth pointing out that this doesn't work with -i.

      --
      John.

Re: need help:insert a line in a textfile
by perl_seeker (Scribe) on Sep 12, 2003 at 10:58 UTC
    You can write the following lines in your Perl editor and then execute it:
    my $line="Whatever line you want to insert"; open FH, '>mytextfile.txt' or die $!; print FH $line; close FH;
    Thanx:)