Amit Moses Albert
Amit Moses Albert

Reputation: 123

Perl - Append to last line of a file (onto same line)

Can someone let me know how to append an output file's last entry based on the current value?

E.g. I am generating an output .txt file, say:

a b c d 10

With some processing I get value 20 and now I want that value to be assigned and aligned with previous set, making it:

a b c d 10 20

Upvotes: 12

Views: 46582

Answers (4)

lutaoact
lutaoact

Reputation: 4429

read the whole file first, you can do it by this subroutine read_file:

sub read_file {
    my ($file) = @_;
    return do {
        local $/;
        open my $fh, '<', $file or die "$!";
        <$fh>
    };
}

my $text = read_file($filename);
chomp $text;
print "$text 20\n";

Upvotes: 1

Gilles Qu&#233;not
Gilles Qu&#233;not

Reputation: 185161

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

Upvotes: 6

Olaf Dietsche
Olaf Dietsche

Reputation: 74028

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.

Upvotes: 13

TLP
TLP

Reputation: 67908

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.

Upvotes: 5

Related Questions