Re: [問題] 兩檔案資料合併
※ 引述《corny (玉咪)》之銘言:
: 我有兩個檔案
: 這兩個檔案都是好幾萬筆
: a.txt b.txt
: ------------- -------------
: abc111 abc123 abc555 abc111
: abc222 abc124 cde666 cde123
: cde333 cde125
: cde444 cde126
: ------------- -------------
: 目標是要知道 a.txt 跟 b.txt 第一欄的前三個字元是不是相同
: 並且抓出該行輸出到 c.txt
: c.txt
: ---------------------------
: abc111 abc123 abc555 abc111
: abc222 abc124 abc555 abc111
: cde333 cde125 cde666 cde123
: cde444 cde126 cde666 cde123
: ---------------------------
: 現在寫好了一個shell script如下
: 不過執行效率非常差
: 全部跑完需要好幾個小時
: 在網路上找到一些關於perl的資訊
: 不過完全沒有接觸過這個語言
: 不知道perl是不是能快速的處理
: while read line1
: do
: temp1=$(echo $line1 | awk '{print substr($1,1,3)}')
: while read line2
: do
: temp2=$(echo $line2 | awk '{print substr($1,1,3)}')
: [ $temp1 == $temp2 ] && echo $line2 $line1 >> c.txt
: done < a.txt
: done < b.txt
不知道下面的程式符不符合你的要求?
#!/usr/bin/perl
use warnings;
use strict;
use Tie::File;
tie my @line_a, 'Tie::File', 'a.txt' or die "cannot open file 'a.txt'\n";
tie my @line_b, 'Tie::File', 'b.txt' or die "cannot open file 'b.txt'\n";
open my $c_txt, '>', 'c.txt' or die "cannot open file 'c.txt'\n";
my %cache = ();
my $lnum = 0;
for my $line (@line_a)
{
my $prefix = substr($line, 0, 3);
push @{$cache{$prefix}}, $lnum++;
}
for my $line (@line_b)
{
my $prefix = substr($line, 0, 3);
next if !exists($cache{$prefix});
for my $lnum (@{$cache{$prefix}})
{
print {$c_txt} "$line_a[$lnum] $line\n";
}
}
假設 a.txt 有 M 行,而 b.txt 有 N 行
你的迴圈就要跑 M*N 次 (複雜度為 O(N*M))
再加上你是用 shell script 實作
它要不斷 spawn 新行程來跑 $(...) 內的程式
而 ">> c.txt" 和 "< a.txt" 會不斷開啟和關閉檔案
最後就是印象中 "while read" 並不適合用在讀取大資料量的檔案(速度會很慢)
所以自然快不了
我的做法為先讀取 a.txt,然後用雜湊(hash)儲存每行前 3 個字元與其所在的行數,
之後再讀取 b.txt,由雜湊查詢其在 a.txt 相應的行數
因為查詢雜湊鍵值的複雜度為 O(1),
所以整個程式的複雜度降為 O(N+M)
這是用空間(雜湊)來換取時間
而讀取指定的行數是由 Tie::File 這個 module 去處理的
( http://perldoc.perl.org/Tie/File.html )
它的讀取速度是程式最大的瓶頸
希望對你有幫助~
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 61.230.178.183
推
03/21 03:09, , 1F
03/21 03:09, 1F
推
03/21 04:37, , 2F
03/21 04:37, 2F
→
03/21 04:37, , 3F
03/21 04:37, 3F
→
03/21 04:37, , 4F
03/21 04:37, 4F
→
03/21 04:37, , 5F
03/21 04:37, 5F
→
03/21 04:38, , 6F
03/21 04:38, 6F
推
03/21 10:50, , 7F
03/21 10:50, 7F
→
03/21 10:50, , 8F
03/21 10:50, 8F
→
03/21 13:40, , 9F
03/21 13:40, 9F
推
03/21 19:11, , 10F
03/21 19:11, 10F
→
03/21 22:34, , 11F
03/21 22:34, 11F
討論串 (同標題文章)