perl 合併多個文件一例

 

這個問題是cu上有人提出的,感受具備表明性,特意記錄一下web

好比a 文件 內容以下
a=11  b=http://www.baidu.com/baicd   c=xxx/baidu.apk
a=12  b=http://www.sina.com/xxx  c=xxx/sina.apk
a=13  b=http://www.qq.com/sdfsd  c=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,,sql

 

  
  
  
  
  1. use strict; 
  2. use warnings; 
  3. use Data::Dumper; 
  4. my (%hash1,%hash2); 
  5.    open FC,"c.txt" or die "$!"
  6.     while(<FC>){ 
  7.       chomp;                   #把C文件映射爲HASH表,用於替換 
  8.         /(\S+),(\S+)/; 
  9.        $hash2{$1}=$2; 
  10.     close FC; 
  11. open FA,"a.txt" or die "$!"
  12. while(<FA>){ 
  13.     my($num,$url,$domain,$apk1); 
  14.     s/a=(\d+)\s+\w+=(http:\/\/([^\/]+)\/\S+)\s+[^\/]+\/(\S+)/ 
  15.     ($num,$url,$domain,$apk1)= ($1,$2,$3,$4); 
  16.     /xeg; 
  17.     $apk1 =~ s/($apk1)/$hash2{$1}? $hash2{$1}:"$1"/eg; 
  18.    push @{$hash1{$domain}},$num,$url,$apk1; 
  19. open FB,"b.txt" or die "$!"
  20.  while(<FB>){ 
  21.     chomp; 
  22.     /(\S+),(\S+)(?{push @{$hash1{$1}},$2})/; 
  23.  } 
  24.  close FB; 
  25. for (sort keys%hash1){ 
  26.     my @arr; 
  27.     unless(defined$hash1{$_}[3]){ 
  28.        push  @arr ,$hash1{$_}[0],$hash1{$_}[1],$hash1{$_}[2],",",;  
  29.     }else
  30.     push @arr ,$hash1{$_}[0],$hash1{$_}[1],$hash1{$_}[3],$hash1{$_}[2]; 
  31.     } 
  32.     print join(",",@arr)."\n"
  33. 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
相關文章
相關標籤/搜索