Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl - Append to last line of a file

Tags:

append

perl

I am a Perl novice, can someone please let me know how to append an output file's last entry based on the current value? E.g. I am generating a output txt file say

a b c d 10

With some processing I get value 20 and now I want this value 20 to be assigned and aligned with previous set which is

a b c d 10

and make it as

a b c d 10 20
like image 865
Amit Moses Albert Avatar asked Apr 03 '13 15:04

Amit Moses Albert


3 Answers

Assuming the last line has no newline

use strict;
use warnings;

open(my $fd, ">>file.txt");
print $fd " 20";

If the last line already has a newline, the output will end up on the next line, i.e.

a b c d 10
 20

A longer version working in either case would be

use strict;
use warnings;

open(my $fd, "file.txt");
my $previous;
while (<$fd>) {
    print $previous if ($previous);
    $previous = $_;
}

chomp($previous);
print "$previous 20\n";

However, this version doesn't modify the original file.

like image 189
Olaf Dietsche Avatar answered Nov 20 '22 18:11

Olaf Dietsche


Try doing this

one-liner version

perl -pe 'eof && do{chomp; print "$_ 20"; exit}' file.txt

script version

#!/usr/bin/env perl

use strict; use warnings;

 while (defined($_ = <ARGV>)) {
    if (eof) {
        chomp $_;
        print "$_ 20";
        exit;
    }
}
continue {
    die "-p destination: $!\n" unless print $_;
}

Sample Output

$ cat file.txt
a b c d 08
a b c d 09
a b c d 10


$ perl -pe 'eof && do{chomp; print "$_ 20"; exit}' file.txt
a b c d 08
a b c d 09
a b c d 10 20
like image 43
Gilles Quenot Avatar answered Nov 20 '22 18:11

Gilles Quenot


perl -0777 -pe 's/$/ 20/' input.txt > output.txt

Explanation: Read the whole file by setting input record separator with -0777, perform a substitution on the data read that matches the file ending, or right before the last newline.

You can also use the -i switch to do in-place edit of the input file, but that method is risky, since it performs irreversible changes. It can be used with backup, e.g. -i.bak, but that backup is overwritten on multiple executions, so I usually recommend using shell redirection instead, as I did above.

like image 40
TLP Avatar answered Nov 20 '22 19:11

TLP