ty9919 发表于 2018-8-31 09:11:20

perl 合并多个文件一例

  这个问题是cu上有人提出的,感觉具有代表性,特地记录一下
  比如a 文件 内容如下
  
a=11b=http://www.baidu.com/baicd   c=xxx/baidu.apk
  
a=12b=http://www.sina.com/xxxc=xxx/sina.apk
  
a=13b=http://www.qq.com/sdfsdc=xxx/qq.akc
  
b 文件内容如下
  
www.baidu.com,111
  
www.sina.com,112
  
c 文件内容如下
  
baidu.apk,123
  
sina.apk,12223
  
结果
  
11,http://www.baidu.com/baicd   ,111,123
  
12,http://www.sina.com/xxx,112,12223
  
13,http://www.qq.com/sdfsd,qq.akc,,
  


[*]use strict;
[*]use warnings;
[*]use Data::Dumper;
[*]my (%hash1,%hash2);
[*]   open FC,"c.txt" or die "$!";
[*]    while(){
[*]      chomp;                   #把C文件映射为HASH表,用于替换
[*]      /(\S+),(\S+)/;
[*]       $hash2{$1}=$2;
[*]}
[*]    close FC;
[*]open FA,"a.txt" or die "$!";
[*]while(){
[*]    my($num,$url,$domain,$apk1);
[*]    s/a=(\d+)\s+\w+=(http:\/\/([^\/]+)\/\S+)\s+[^\/]+\/(\S+)/
[*]    ($num,$url,$domain,$apk1)= ($1,$2,$3,$4);
[*]    /xeg;
[*]    $apk1 =~ s/($apk1)/$hash2{$1}? $hash2{$1}:"$1"/eg;
[*]   push @{$hash1{$domain}},$num,$url,$apk1;
[*]}
[*]open FB,"b.txt" or die "$!";
[*] while(){
[*]    chomp;
[*]    /(\S+),(\S+)(?{push @{$hash1{$1}},$2})/;
[*] }
[*] close FB;
[*]for (sort keys%hash1){
[*]    my @arr;
[*]    unless(defined$hash1{$_}){
[*]       push@arr ,$hash1{$_},$hash1{$_},$hash1{$_},",",;
[*]    }else{
[*]    push @arr ,$hash1{$_},$hash1{$_},$hash1{$_},$hash1{$_};
[*]    }
[*]    print join(",",@arr)."\n";
[*]}
[*]output
[*]

[*]11,http://www.baidu.com/baicd,111,123
[*]13,http://www.qq.com/sdfsd,qq.akc,,
[*]12,http://www.sina.com/xxx,112,12223



页: [1]
查看完整版本: perl 合并多个文件一例