2014-03-05 72 views
2

設置:洗牌在相同的順序的多個文件

我有50個文件,每個具有25000行。

待辦事項:

我需要「以相同的順序」洗牌所有的人。 例如: -

如果洗牌前:

File 1 File 2 File 3 
A  A  A 
B  B  B 
C  C  C 

再洗牌後,我應該得到:

File 1 File 2 File 3 
B  B  B 
C  C  C 
A  A  A 

即在文件中相應的行應該在相同的順序進行改組。

此外,洗牌應該是確定性的,即如果我給文件A作爲輸入,它應該總是產生相同的洗牌輸出。

我可以編寫一個Java程序來做到這一點,可能是一個腳本。就像洗牌數在1到25000之間,並將其存儲在一個文件中,比如shuffle_order。然後,一次只處理一個文件,並根據shuffle_order對現有行進行排序。但是有沒有更好的/快捷的方法來做到這一點?

如果需要更多信息,請讓我知道。

+0

的大問題你有(但米ay還沒有注意到)是如何將一個文件放入預定的順序......特別是如果你不能假設整個文件可以一次存儲在內存中。您可能需要創建「中間」文件(每行具有預定順序的行),然後以ping/pong模式瀏覽這些文件,直到您最終獲得一個文件。 – ErstwhileIII

+0

如果您必須處理「文件不適合內存」,請調整您的問題,我可以爲您提供有關「合併排序」過程的建議。 – ErstwhileIII

回答

0

可能效率非常低,但嘗試如下:

#!/bin/bash 

arr=($(for i in {1..25000}; do 
    echo "$i" 
done | shuf)) 


for file in files*; do 
    index=0 
    new=$(while read line; do 
     echo "${arr[$index]} $line" 
     ((index++)) 
    done < "$file" | sort -h | sed 's/^[0-9]\+ //') 
    echo "$new" > "$file" 
done 
1

下僅使用基本的bash命令。普林西是:

A B C 
-------- 
a1 a2 a3 
b1 b2 b3 
c1 c2 c3 
d1 d2 d3 
e1 e2 e3 
f1 f2 f3 
g1 g2 g3 
h1 h2 h3 
i1 i2 i3 
j1 j2 j3 

  • 產生隨機順序(數字)
  • 順序依次

代碼

#!/bin/bash 
case "$#" in 
    0) echo "Usage: $0 files....." ; exit 1;; 
esac 

ORDER="./.rand.$$" 
trap "rm -f $ORDER;exit" 1 2 
count=$(grep -c '^' "$1") 

let odcount=$(($count * 4)) 
paste -d" " <(od -A n -N $odcount -t u4 /dev/urandom | grep -o '[0-9]*') <(seq -w $count) |\ 
    sort -k1n | cut -d " " -f2 > $ORDER 

#if your system has the "shuf" command you can replace the above 3 lines with a simple 
#seq -w $count | shuf > $ORDER 

for file in "[email protected]" 
do 
    paste -d' ' $ORDER $file | sort -k1n | cut -d' ' -f2- > "$file.rand" 
done 

echo "the order is in the file $ORDER" # remove this line 
#rm -f $ORDER       # and uncomment this 
             # if dont need preserve the order 

paste -d " " *.rand #remove this line - it is only for showing test result 

從輸入文件中的所有文件

會使A.rand B.rand C.rand下一個示例內容

g1 g2 g3 
e1 e2 e3 
b1 b2 b3 
c1 c2 c3 
f1 f2 f3 
j1 j2 j3 
d1 d2 d3 
h1 h2 h3 
i1 i2 i3 
a1 a2 a3 

實際測試 - genereting 50個文件有25K線

line="Consequatur qui et qui. Mollitia expedita aut excepturi modi. Enim nihil et laboriosam sit a tenetur." 
for n in $(seq -w 50) 
do 
    seq -f "$line %g" 25000 >file.$n 
done 

運行腳本

bash sorter.sh file.?? 

結果在我的筆記本

real  1m13.404s 
user  0m56.127s 
sys  0m5.143s