Perl - 追加到文件的最后一行(同一行)

12
有人可以告诉我如何根据当前值将输出文件的最后一个条目追加到文件中吗?
例如,我正在生成一个输出 .txt 文件,比如:
a b c d 10

经过一些处理,我得到了值20,现在我想将该值分配并与先前设置对齐,使其变为:

a b c d 10 20
4个回答

13

假设最后一行没有换行符

use strict;
use warnings;

open(my $fd, ">>file.txt");
print $fd " 20";
如果最后一行已经有一个换行符,那么输出将会出现在下一行。即:
a b c d 10
 20

一个更长的版本,无论哪种情况下都可以工作。

use strict;
use warnings;

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

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

然而,这个版本不会修改原始文件。


6

试试这个

一行代码 版本

perl -pe 'eof && do{chomp; print "$_ 20"; exit}' file.txt
#!/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

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

说明:通过设置输入记录分隔符为-0777来读取整个文件,在读取的数据上执行匹配文件结尾或者最后一个换行符前面的替换。

您也可以使用-i开关对输入文件进行原地编辑,但是这种方法很危险,因为它会进行不可逆转的更改。它可以与备份一起使用,例如-i.bak,但是该备份在多次执行时会被覆盖,因此我通常建议使用Shell重定向,就像我上面所做的那样。


1

首先要读取整个文件,可以使用以下子程序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";

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接