2012-11-15 37 views
1

我需要編寫一個交叉兩個不同文件內容的腳本。例如,執行」 ./inter2files文件1文件2' 會給我:Shell的交錯腳本

文件1,一號線
文件2 *一號線
文件1,2號線
文件2 * 2號線

我到目前爲止的代碼是:

exec 30< file1 
exec 40< file2 
read line1 <& 30 
read line2 <& 40 
echo $line1 
echo $line2 
+0

而這並不因爲工作...? –

回答

0

想通了一個Perl腳本

#!/usr/bin/perl 

do { open($fh[$_], "<$ARGV[$_]") or die("'$ARGV[$_]' does not exist") } for (0..$#ARGV); 

for ($i=0;;$i++) { 
    $j=$#ARGV+1; 

    $fh = $fh[$i%$j]; 
    if ($_ = <$fh>) { 
      print $_; 
    } else { 
      $end |= 2**($i%$j); 
    } 

    if($end == (2**($j))-1) { 
      last; 
    } 
} 

close($_) for(@fh); 
4

你可以做到這一點與paste

paste -d "\n" file1 file2 > output_file 
0
declare -a f1=(`cat file1`) 
declare -a f2=(`cat file2`) 
count=`echo ${#f1[@]}` # Number of elements in the array 
#### assuming the line counts are the same between file1 and file2 
i=0 
while [ ${i} -le ${count} ] 
do 
    echo ${f1[${i}]}" "${f2[${i}]} 
    ((i=${i}+1)) 
done 

,數組聲明使用的內存空間,如果你的文件是巨大的,可能會導致你不可預知的行爲,但如果你只處理幾百行價值文件的時間,這種方法應該工作。