如何将输出写入txt文件?

时间:2019-09-12 06:32:42

标签: perl

我想合并两个文件并打印到一个txt文件中。

我已经成功合并了两个数据,但是无法将其打印到txt文件中。到目前为止,输出仅以xterm打印。

输入1:

a123
b
c
d
e
f
g

输入2:

a123
x
y
x
c
v

当前输出显示在xterm中,而不是txt文件中。

a123
b
c
d 
e
f
g
x
y
x
c
v

运行我的脚本:

perl test1.pl file1 file2
#!/usr/bin/perl
use strict;
use warnings;
use autodie;
my $files = $#ARGV; # get number of files - 1
while (my $file = shift @ARGV) {
   open my $fh, "<", $file;
   <$fh> unless $files == @ARGV;  #discard header unless first file
   printf while <$fh>;
}

保存一个txt文件

2 个答案:

答案 0 :(得分:1)

将.txt文件中的脚本输出重新映射。

perl test1.pl file1 file2 > output.txt

答案 1 :(得分:0)

如果要在脚本中以编程方式编写文本文件,则可以使用以下脚本。

此脚本还将文本文件名也用作命令行参数,最后一个命令行参数将用作写入内容的文件名。

#!/usr/bin/perl -w
use strict;

my $outfile = $ARGV[$#ARGV];
my @files = @ARGV[0..$#ARGV-1];

open my $outf, ">", $outfile or
    die "Unable to open the file: $!";

my $i = 0;
foreach my $file (@files) {
    open my $f, "<", $file;
    while (<$f>) {
        next if ($.== 1 && $i>0);
        print $outf $_;
    }
    close $f;
    $i++;
}

close $outf;

执行脚本的命令:

perl test1.pl file1 file2 file3.txt