[英]How can I replace a column of one file with a column of another using Perl?
假设文件1有两列,如下所示:
fuzz n. flowering shrub of the rhododendron family dyspeptic adj. bright blue, as of the sky dysplexi adj. of Byzantium or the E Roman Empire eyrie adj. of the Czech Republic or Bohemia azalea adj. suffering from dyslexia Czech adj. suffering from dyspepsia Byzantine n. eagle's nest azure n. mass of soft light particle
文件2只有一个笨拙,看起来像:
azalea azure Byzantine Czech dyslexic dyspeptic eyrie fuzz
我希望将文件1的第一列替换为文件2的列。因此,文件3应该如下所示:
azalea n. flowering shrub of the rhododendron family azure adj. bright blue, as of the sky Byzantine adj. of Byzantium or the E Roman Empire Czech adj. of the Czech Republic or Bohemia dyslexic adj. suffering from dyslexia dyspeptic adj. suffering from dyspepsia eyrie n. eagle's nest fuzz n. mass of soft light particle
我感觉有一种或另一种简单的方法可以完成这种工作,很可能那里有一些方便的模块,但就目前而言,即使以最低效的方式,我也无法做到。 我尝试了一堆像
while<$line1 = file1>{
while<$line2 = file2>{
join $line,$line2
但根本没有运气。 有人可以向我指出正确的方向吗? 与往常一样,感谢您的指导。
如果要同时阅读两行,请尝试以下操作:
while(defined(my $line1 = <file1>)
and defined(my $line2 = <file2>)) {
# replace contents in $line1 with $line2 and do something with $line1
}
一旦一行用完,它将立即停止工作,因此,最好在此循环结束时查看两个文件是否为空:
die "Files are different sizes!\n" unless eof(file1) == eof(file2);
当然,在现代Perl中,您可以将文件句柄存储在按词法定义的变量中,如下所示:
open my $fh, ...
然后用漂亮的词法范围<$filehandles>
替换丑陋的全局<FILEHANDLES>
<$filehandles>
。 更好,它使
我读此文件是因为您要输出与第二个文件类似的第一个文件。 重新阅读之后,似乎您只想替换该列,而无需更改顺序。 这是假设您可以处理打开文件的解决方案。
while(($line1 = <FILE1>) && ($line2 = <FILE2>)){
chomp $line2;
$line1 =~ s/^\w+/$line2/;
print FILE3 $line1;
}
这是我最初的解决方案,按照条目在第二个文件中出现的顺序对它们进行排序。
创建文件1的哈希。
$dictionary = {}
while (<FILE1>){
m/^(\w+)\s+(.*)$/;
$dictionary{$1}=$2;
}
查找文件2中每个键的定义并打印连接的行
while (<FILE2>){
$key =~ s/\s*//g;
print FILE3 "$key\t\t$dictionary{$key}\n";
}
一步一步思考您想做什么。
然后继续这样做,直到用完一个文件或另一个文件的行。
这是您需要的一些部件:
open(my $filehandle, '<', 'filename') or die "Can't open filename";
my $line = <$filehandle>;
split()
甚至substr()
exit if !$line
,则exit if !$line
; 您可以在* nix上使用“ cut -c 10- file1 |粘贴file2-”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.