perl代码合并多个文本文件
发布时间:2020-12-16 06:29:10 所属栏目:大数据 来源:网络整理
导读:我有多个文本文件.我已编写代码通过 shell输入2个文件并合并它们.但我如何合并多个文件.系统命令是有用的. my @a = read_file($file1) or die "couldn't read $file1 - $!";my @b = read_file($file2) or die "couldn't read $file2 - $!";my $combined = {}
我有多个文本文件.我已编写代码通过
shell输入2个文件并合并它们.但我如何合并多个文件.系统命令是有用的.
my @a = read_file($file1) or die "couldn't read $file1 - $!"; my @b = read_file($file2) or die "couldn't read $file2 - $!"; my $combined = {}; # hashref my $i=0; foreach (@a) { chomp; $combined->{$i}{b} = '' unless defined $combined->{$i}{b}; $combined->{$i++}{a} = $_; } $i=0; foreach (@b) { chomp; $combined->{$i}{a} = '' unless defined $combined->{$i}{a}; $combined->{$i++}{b} = $_; } foreach my $i (sort {$a<=>$b} keys %$combined) { print $combined->{$i}{a},("t" x 2),$combined->{$i}{b},"n"; } 解决方法
据我所知,您可以同时读取两行文件的一行,并打印用制表符分隔的每一行,如:
use warnings; use strict; die unless @ARGV == 2; open my $fha,q|<|,$ARGV[0] or die; open my $fhb,$ARGV[1] or die; while ( my $a = <$fha>,my $b = <$fhb> ) { chomp( $a,$b ); printf qq|%stt%sn|,$a,$b; } 如果文件具有不同的行数,则此脚本将不起作用.对于这种情况,您将需要另一种方法. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |