请多指教 perl 多个文件合并

lwgzhy12345 2010-03-17 04:31:22
最近刚学习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
由于文件数量比较多,有好几十个,希望能用一个循环,批量处理。
希望大家指教,先在此谢谢各位!
...全文
924 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
chendaming007 2010-03-19
  • 打赏
  • 举报
回复
用数组解决,定义一个空数组,把文件a和文件b的数字以你需要的格式放到新数组中,最后把新数组写入文件c

#!/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);
}
lvyinghong 2010-03-18
  • 打赏
  • 举报
回复

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




自己测试一下吧
lwgzhy12345 2010-03-18
  • 打赏
  • 举报
回复
我的文件的行数是一样的,每行不止一列的话就是写入第一个文件的,再写入第二个文件的。就像下面的例子:
文件1:1.txt
1 2
3 4
5 6
7 8
文件2:2.txt
a
b
c
d
希望合并后的到结果文件:3.txt
1 2 a
3 4 b
5 6 c
7 8 d
非常谢谢!
Aylazhang 2010-03-18
  • 打赏
  • 举报
回复
你说的只是理想情况。
如果两个文件行数不一样,或者每行不止一列等等这样的情况,该怎么处理?
lwgzhy12345 2010-03-18
  • 打赏
  • 举报
回复
合并规则是这样的:
文件1:1.txt
1
3
5
7
文件2:2.txt
a
b
c
d
希望合并后的到结果文件3.txt
1 a
2 b
3 c
4 d
就是按原来的顺序一列一列排,用tab键作为分隔符。
clchun4352 2010-03-18
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 lvyinghong 的回复:]

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" . $……
[/Quote]
wangshun424 2010-03-18
  • 打赏
  • 举报
回复

#! 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++
}


测试了下,还行。
lwgzhy12345 2010-03-18
  • 打赏
  • 举报
回复
问题补充:
由于我的文件数量比较多,我81个,每个文件一列数据,行数相同,我希望能把这81个文件,通过文件操作,放到一个文件里面,就是得到一个 81列的文件。
Aylazhang 2010-03-17
  • 打赏
  • 举报
回复
关键的一点:你的合并规则没有说清楚。

37,717

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧