最近刚学习perl,在用perl处理数据时,遇到一个难题:我有多个文本数据,想把他们正和到一个文件里面,该如何弄?
示例如下
1.txt
1
2
3
4
5
2.txt
6
7
8
9
10
想合并后得
3.txt
1 6
2 7
3 8
4 9
5 10
由于文件数量比较多,有好几十个,希望能用一个循环,批量处理。
希望大家指教,先在此谢谢各位!
------解决方案--------------------
关键的一点:你的合并规则没有说清楚。
------解决方案--------------------
- Perl code
my $text1 = `cat 1.txt`; my $text2= `cat 2.txt`; my @line1 = split ('\n',$text1); my @line2 = split ('\n',$text2); for (my $i =0;$i < $#line1 ;$i++) { $line1[$i] = $line1[$i]."\t" . $line2[$i] . "\n"; } foreach (@line1) { `echo $_ >> 3.txt` ; }
------解决方案--------------------
- Perl code
#! perl my $dir = "d:\\test\\"; opendir DIR,$dir or die "can't open dir $dir : $!"; my @file = grep /[\d\w_]+\.txt/,readdir DIR; print @file; open ROWS,"$dir$file[0]" or die "can't open file $dir$file[0] : $!"; my @rows = <ROWS>; open RESULT,'>d:\result.text' or die "can'open file d:\result.text: $!"; foreach my $row(1..@rows){ my $count = "A"; my $str = ""; foreach my $file_name(@file){ my $handel = "FILE$count"; open $handel,"$dir$file_name" or die "can't open file $file_name : $!"; my @context = <$handel>; chomp @context; $str = $str.$context[$row-1]."\t"; $count++; @context = (); close $handel; } $str .= "\n"; print RESULT $str; $row++ }
------解决方案--------------------
用数组解决,定义一个空数组,把文件a和文件b的数字以你需要的格式放到新数组中,最后把新数组写入文件c
[code=Perl][/code]
#!/usr/bin/perl
system(":>./c");
@c=();
open (FH, "./a")||die "Cannot open the file!\n";
my @a=<FH>;
close(FH);
open (FH, "./b")||die "Cannot open the file!\n";
my @b=<FH>;
close(FH);
$len=$#a;
for($i=0;$i<=$len;$i++)
{
chomp $a[$i];
$c[$i]=$a[$i]."\t".$b[$i];
open (FH, ">>./c")||"Canot open the file!\n";
syswrite(FH,"$c[$i]\n");
close(FH);
}