Perl:如何在新的文本文件中编写脚本的输出

时间:2014-10-25 10:41:51

标签: perl

首先,我是perl上的一个菜鸟,我试图在互联网上找到这个问题的答案,但无法获得(或了解)它... 所以,我有一个脚本可以扫描文本文件并写入除A开头的所有行。

#!/usr/bin/perl
use strict;
use warnings;
open (my $file, "<", "/file.txt") or die "cannot open < file.txt $!";
while (<$file>) {
    unless (/^A/) {
        print;
    }
}  

有效。但是我在终端中得到了这个脚本的结果。现在,我只想将这些结果保存在新的文本文件中。 有人能帮助我吗?

非常感谢!

1 个答案:

答案 0 :(得分:2)

只需打开另一个文件并打印数据即可。

#!/usr/bin/env perl
use strict;
use warnings;

my $infile  = 'input.txt';
my $outfile = 'output.txt';

open my $infh,  "<", $infile  or die "Can't open $infile: $!";
open my $outfh, ">", $outfile or die "Can't open $outfile: $!";

while (<$infh>) {
    print $outfh $_ unless /^A/;
}

close($infh);
close($outfh);

但是,一般来说,你可以使用一些perl magic与shell重定向相结合。整个脚本将变得简单oneliner:

$ perl -ne 'print $_ unless /^A/;' input.txt > output.txt
相关问题