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
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.
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 $_;
}
$ 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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With