简体   繁体   English

打开多个文件并将其内容复制到最后打开的文件

[英]open multiple files and copy their content to the last file opened

I'd like to open multiple files and copy their content to the last file opened 我想打开多个文件并将其内容复制到上次打开的文件中

input: 输入:

file1.txt -> 1111
file2.txt -> 2222
file3.txt -> 3333

output should be: 输出应为:

file1.txt -> 1111
file2.txt -> 2222
file3.txt -> 1111 2222 3333

my code 我的代码

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

my %data;
my @FILES = @ARGV;

foreach my $file (@FILES) {
    local $/ = undef;
    open my $fh, '<', $file;
    $data{$file} = <$fh>;

foreach my $key (keys %data) {
    open (OUTFILE, ">".$file) or die "#!\n";
    print OUTFILE "$key";
}
}
close(OUTFILE);
exit;

output from the code: 代码输出:

file1.txt -> file1.txt
file2.txt -> file1.txt
file3.txt -> file3.txt

It's not reading the files because it prints the file name instead of it's content and also I can't seem to print the content of previous files into the last file. 它不读取文件,因为它会打印文件名而不是内容,而且我似乎也无法将先前文件的内容打印到最后一个文件中。 Thanks in advance 提前致谢

You need to write to a different file, otherwise you'd rewrite the last file before reading its contents. 您需要写入另一个文件,否则在读取文件内容之前,需要重写最后一个文件。 You can then write to the output directly when reading the files, no need to store the contents in a hash. 然后,您可以在读取文件时直接写入输出,而无需将内容存储在哈希中。 If you want to use the hash, print the values, not the keys. 如果要使用哈希,请打印值,而不是键。

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

my $output_file = $ARGV[-1];
my $tmp = $output_file . "-tmp$$";

open my $OUT, '>', $tmp or die $!;

while (<>) {
    print {$OUT} $_;
}

rename $tmp, $output_file or die $!;
close $OUT or die $!;

Also here is some code that will do such task: 另外,这里有一些代码可以完成这样的任务:

#...
my ($lastfile, $data) = pop @FILES;

for (@FILES) {
    open my $fh, "<$_" or die "$!";
    $data .= join '', <$fh> , "\n"; # you can change the "\n" delimiter
    close $fh
}
open my $fh, '+<',$lastfile or die "$!";
$data .= join '', <$fh>;
seek $fh, 0, 0; # allows to write from the beginning (in this case re-write file)
print $fh $data;
close $fh; 

Read here about opening file handles in both read and write mode. 在此处阅读有关在读写模式下打开文件句柄的信息。
Also take care about which delimiter you use to make the result file more readable. 还请注意使用哪个定界符使结果文件更易读。


EDIT 编辑
You can even do so: 您甚至可以这样做:

$data .= "$_ -> " . join '', <$fh> , "\n";

in first join and 在第一次加入

$data .= "$lastfile -> " . join '', <$fh>;

in second if you want to remember what content was in each file. 如果您想记住每个文件中的内容,请在第二秒。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM