how to write output into txt file?

I want to merge two files and print into one txt file.

I already successful merge two data but unable to print it into txt file. by now, the output just printed in xterm.

input 1:

a123
b
c
d
e
f
g

input 2:

a123
x
y
x
c
v

current output was displayed in xterm not in txt file.

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

run my script:

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>;
}

save inside one txt file

Upvotes: 0

Views: 395

Answers (2)

rprakash
rprakash

Reputation: 510

If you want to write the text file programmatically in the script then you can use following script.

This script takes the text file name also as a command line argument, last command line argument would used as the file name in which the content will be written.

#!/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;

Command to execute the script :

perl test1.pl file1 file2 file3.txt

Upvotes: 0

Redirct the output of script in .txt file.

perl test1.pl file1 file2 > output.txt

Upvotes: 1

Related Questions