2017-10-26 13 views
0

Bashで事前に定義したリストに基づいて配列の順序をソートするにはどうすればよいですか。定義済みリストに基づくソート

私は

fixed=(john doe mary ben) 

に私は私が私が

    が必要

    のbashコードを満たすために必要ないくつかの基準があり、それは

    changetimetotime=(ben-5 doe-1 john-1) 
    

    を変更するアレイを定義済みリストに

  1. T彼はchangetimetotime配列の量は必要ありません3、時には1値ですが、最大値は4です。

  2. 固定配列は名前のみを提供し、changetimetotimeはバージョン番号も指定します。両方の条件が満たされたら

、配列は

changetimetotime=(john-1 doe-1 ben-5) 

以下に変更されますと私は、ループの外にchangetimetotime配列にアクセスする必要があります。

助けてください。

答えて

1

要素は常にクイック

# an associative array to decode names to an int 
declare -A hash=([john]="1" [doe]="2" [mary]="3" [ben]="4") 

# or to fill from fixed array 
# declare -A hash=() 
# for i in "${!fixed[@]}"; do hash[${fixed[i]}]=$i; done 

# function used to compare two elements 
# exit status is success (0) if first is less or equal to second 
is_ordered() { 
    # if string after name can contain many '-', % may be changed to %% to remove logest matched suffix 
    # extract names from elements 
    local k1=${1%-*} k2=${2%-*} 
    local v1=${hash[$k1]} v2=${hash[$k2]} 
    (($v1<=$v2)) 
} 

# recursive quick sort 
qsort() { 
    local l=() g=() p=$1 
    r=() 
    shift || return 
    for i; do 
     if is_ordered "$i" "$p"; then 
      l+=("$i") 
     else 
      g+=("$i") 
     fi 
    done 

    qsort "${g[@]}" 
    g=("${r[@]}") 
    qsort "${l[@]}" 
    l=("${r[@]}") 

    r=("${l[@]}" "$p" "${g[@]}") 
} 

qsort "${changetimetotime[@]}" 
changetimetotime=("${r[@]}") 
を使用して、

fixed=(john doe mary ben) 

# to fill an associative array from fixed array 
# if supported (bash >4) otherwise use a decoding function 
declare -A hash=() 
for i in "${!fixed[@]}"; do hash[${fixed[i]}]=$i; done 

changetimetotime=(ben-5 doe-1 john-1) 
newchangetimetotime=() 
for element in "${changetimetotime[@]}"; do 
    index=${hash[${element%%-*}]} 
    newchangetimetotime[index]=$element 
done 

echo "${newchangetimetotime[@]}" 

# overwrite array reindexing keys 
changetimetotime=("${newchangetimetotime[@]}") 

そうでない一般的なケースをスパースアレイを使用して事前に定義されたセットに含まれている場合

関連する問題