看板 Perl 關於我們 聯絡資訊
※ 引述《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
iFEELing: 善用 HASH , 記憶體現在不貴 , 不用那麼省... 03/21 03:09
giacch:open(READ, 'b.txt'); chomp(@TMP=<READ>); close(READ); 03/21 04:37
giacch:foreach(@TMP) { $b{$1}=$_ if(/^(...)/); } 03/21 04:37
giacch:open(READ, 'a.txt'); chomp(@TMP=<READ>); close(READ); 03/21 04:37
giacch:foreach(@TMP) { print $_.' '.$b{$1}."\n" if(/^(...)/); 03/21 04:37
giacch:這樣可以跑範例... 03/21 04:38
corny:非常感謝,在redhat上可以正確執行,cygwin上前三行只有b的 03/21 10:50
corny:資料,這是甚麼原因呢? 03/21 10:50
corny:原來是換行符號的問題,不過chomp(@TMP=<READ>)為何沒作用? 03/21 13:40
corny:請問一下~hash之後如何取得各欄位資料?有類似awk的方法嗎 03/21 19:11
frank1983:@fields = split /\s+/, $line; 03/21 22:34