append a text on the top of the file

前端 未结 6 856
借酒劲吻你
借酒劲吻你 2020-12-20 16:29

I want to add a text on the top of my data.txt file, this code add the text at the end of the file. how I can modify this code to write the text on the top of my data.txt f

相关标签:
6条回答
  • 2020-12-20 16:48

    perl -ni -e 'print "Title\n" $.==1' filename , this print the answer once

    0 讨论(0)
  • 2020-12-20 16:52
     perl -pi -e 'print "Title\n" if $. == 1' data.text
    
    0 讨论(0)
  • 2020-12-20 16:53

    Your syntax is slightly off deprecated (thanks, Seth):

    open(MYFILE, '>>', "data.txt") or die $!;
    

    You will have to make a full pass through the file and write out the desired data before the existing file contents:

    open my $in,  '<',  $file      or die "Can't read old file: $!";
    open my $out, '>', "$file.new" or die "Can't write new file: $!";
    
    print $out "# Add this line to the top\n"; # <--- HERE'S THE MAGIC
    
    while( <$in> ) {
        print $out $_;
    }
    close $out;
    close $in;
    
    unlink($file);
    rename("$file.new", $file);
    

    (gratuitously stolen from the Perl FAQ, then modified)

    This will process the file line-by-line so that on large files you don't chew up a ton of memory. But, it's not exactly fast.

    Hope that helps.

    0 讨论(0)
  • 2020-12-20 16:53

    Appending to the top is normally called prepending.

    open(M,"<","data.txt");
    @m = <M>;
    close(M);
    open(M,">","data.txt");
    print M "foo\n";
    print M @m;
    close(M);
    

    Alternately open data.txt- for writing and then move data.txt- to data.txt after the close, which has the benefit of being atomic so interruptions cannot leave the data.txt file truncated.

    0 讨论(0)
  • 2020-12-20 16:58

    See the Perl FAQ Entry on this topic

    0 讨论(0)
  • 2020-12-20 17:02

    There is a much simpler one-liner to prepend a block of text to every file. Let's say you have a set of files named body1, body2, body3, etc, to which you want to prepend a block of text contained in a file called header:

    cat header | perl -0 -i -pe 'BEGIN {$h = <STDIN>}; print $h' body*
    
    0 讨论(0)
提交回复
热议问题