2010-08-18 16 views
8

Formato delle versioni - X.X.X.X.
Dove X - numero.
Qual è il modo migliore per confrontare due versioni?
Io uso seguente codice:Come confrontare le versioni di alcuni prodotti in unix ksh shell?

compareVersions() 
{ 
    VER_1=$1 
    VER_2=$2 

    print -R "$VER_1"| IFS=. read v1_1 v1_2 v1_3 v1_4 
    print -R "$VER_2"| IFS=. read v2_1 v2_2 v2_3 v2_4 

    RESULT="0" 

    if [[ "${v1_1}" -lt "${v2_1}" ]] 
    then 
    RESULT="-1" 
    elif [[ "${v1_1}" -gt "${v2_1}" ]] 
    then 
    RESULT="1" 
    elif [[ "${v1_2}" -lt "${v2_2}" ]] 
    then 
    RESULT="-1" 
    elif [[ "${v1_2}" -gt "${v2_2}" ]] 
    then 
    RESULT="1" 
    elif [[ "${v1_3}" -lt "${v2_3}" ]] 
    then 
    RESULT="-1" 
    elif [[ "${v1_3}" -gt "${v2_3}" ]] 
    then 
    RESULT="1" 
    elif [[ "${v1_4}" -lt "${v2_4}" ]] 
    then 
    RESULT="-1" 
    elif [[ "${v1_4}" -gt "${v2_4}" ]] 
    then 
    RESULT="1" 
    fi 

    echo "$RESULT" 
} 

Ma non mi piace che - è molto semplice.
Forse c'è un modo molto corretto per confrontare le versioni?

+1

Sei sicuro che non sia ksh invece di Bash? Bash non ha il comando 'print' e non puoi reindirizzare al suo' read'. –

+0

Sì, questo è ksh. Ho corretto i tag. –

+2

"non puoi sondare nella sua lettura" - certo che puoi. 'printf" abc \ n "| {leggi x; printf "ha ottenuto $ x \ n"; } ' –

risposta

11

Pure Bash/Ksh:

compareVersions() 
{ 
    typeset IFS='.' 
    typeset -a v1=($1) 
    typeset -a v2=($2) 
    typeset n diff 

    for ((n=0; n<4; n+=1)); do 
    diff=$((v1[n]-v2[n])) 
    if [ $diff -ne 0 ] ; then 
     [ $diff -le 0 ] && echo '-1' || echo '1' 
     return 
    fi 
    done 
    echo '0' 
} # ---------- end of function compareVersions ---------- 
+1

+1 Dovresti comunque rendere tutte le tue variabili locali. –

+0

Hai ragione. Appena risolto –

+0

fgm grazie per la sceneggiatura!Solo perché sono un fanatico e ho bisogno di fare le cose esatte "$ diff -le 0" dovrebbe essere "$ diff -lt 0". Poiché $ diff non sarà mai 0 a questo punto a causa del condizionale precedente. – ptsw

7

Forse potresti usare awk?

echo $VER_1 $VER2 | \ 
awk '{ split($1, a, "."); 
     split($2, b, "."); 
     for (i = 1; i <= 4; i++) 
      if (a[i] < b[i]) { 
       x =-1; 
       break; 
      } else if (a[i] > b[i]) { 
       x = 1; 
       break; 
      } 
     print x; 
    }' 

Non c'è un modo perfetto per farlo. Come mostrato è possibile utilizzare array/loop per i numeri, anche in bash.

+1

Penso che questo sia il mio metodo preferito per la compatibilità, come' sort -V' isn ' È ampiamente supportato abbastanza e l'uso di 'awk' evita la necessità di funzionalità integrate specifiche. – Haravikk

+1

Si potrebbe fare un po 'più breve cambiando il ciclo 'for' in' for (i = 1;! X && i <= 4; ++ i) x = (a [i] b [i])? 1: 0); ' – ldav1s

2

Se si può barare utilizzando Perl nel vostro script di shell, provare è costruito in handling of version strings con operatori di confronto stringa:

V1=1.1.3; V2=1.1 
echo $(perl -e '($x,$y)[email protected]; print $x cmp $y' $V1 $V2) 

Si potrebbe anche fare via con le variabili Perl e basta usare shift:

result=$(perl -e 'print shift cmp shift' $V1 $V2) 

Ma questo non funziona su v ersioni> 10. Così si potrebbe provare questo invece:

perl -e '($a,$b)[email protected]; for ($a,$b) {s/(\d+)/sprintf "%5d", $1/ge}; print $a cmp $b;' 12.1.3 9.0.2 

Lo sprintf di "% 5d" è quello di assicurarsi che funziona anche per Firefox, fino alla versione 99999 ... :-)

Ovviamente , potresti anche usare gli altri operatori di stringa Perl come gt, lt, ge e le.

4

È possibile utilizzare sort -V per ordinare le linee con le versioni e abbinare la versione contro l'output:

% cat sorttest 
#!/bin/sh 

version_lt() { 
    echo "$1\n$2" | sort -V | head -n 1 | grep -q "$1" 
} 

display_versioncmp() { 
    version_lt "$1" "$2" && echo "$1 < $2" || echo "$1 > $2" 
} 

X="1.2.3" 
Y="11.2.3" 
Z="1.22.3" 

display_versioncmp "$X" "$Y" 
display_versioncmp "$Y" "$X" 
display_versioncmp "$X" "$Z" 
display_versioncmp "$Z" "$X" 
display_versioncmp "$Z" "$Y" 
display_versioncmp "$Y" "$Z" 

% ./sorttest 
1.2.3 < 11.2.3 
11.2.3 > 1.2.3 
1.2.3 < 1.22.3 
1.22.3 > 1.2.3 
1.22.3 < 11.2.3 
11.2.3 > 1.22.3 
+2

Sfortunatamente, non bash di ogni piattaforma ha 'sort -V'. (Ad esempio, Mac non può.) – kcrisman

+0

Script non è corretto. Non risolve tutti i casi come 3.22.3> 11.2.3 se l'input è 3 e 11, quindi sicuramente 11 è la versione più alta ma lo script mostra 3 ha una versione più alta. –

+1

@AnandChoubey quale versione di sorta hai? Con il mio (ovvero Ubuntu 12.04) tutto funziona come previsto: 3.22.3> 1.2.3 3.22.3 <11.2.3 # sort --version sort (GNU coreutils) 8.13 – timurb

0

Ho avuto questo problema, e dopo aver risolto sembrava di vedere se ci fosse una risposta migliore già disponibile. La mia versione consente di confrontare stringhe di versioni di lunghezza diverse, ed è la funzione version_ge() di seguito, che dovrebbe essere utilizzata come operatore "maggiore o uguale a", come in

se version_ge "$ version" "1.2.3.4" ; quindi ...

#!/bin/sh 

# Usage: split "<word list>" <variable1> <variable2>... 
# Split a string of $IFS seperated words into individual words, and 
# assign them to a list of variables. If there are more words than 
# variables then all the remaining words are put in the last variable; 
# use a dummy last variable to collect any unwanted words. 
# Any variables for which there are no words are cleared. 
# eg. split 'hello Fred this is Bill' greeting who extra 
# sets greeting=hello who=Fred extra="this is Bill" 
# and split "$list" word list # "pops" the first word from a list 
split() 
{ 
    # Prefix local names with the function name to try to avoid conflicts 
    # local split_wordlist 
    split_wordlist="$1" 
    shift 
    read "[email protected]" <<EOF-split-end-of-arguments 
${split_wordlist} 
EOF-split-end-of-arguments 
} 


# Usage: version_ge v1 v2 
# Where v1 and v2 are multi-part version numbers such as 12.5.67 
# Missing .<number>s on the end of a version are treated as .0, & leading 
# zeros are not significant, so 1.2 == 1.2.0 == 1.2.0.0 == 01.2 == 1.02 
# Returns true if v1 >= v2, false if v1 < v2 
version_ge() 
{ 
    # Prefix local names with the function name to try to avoid conflicts 
    # local version_ge_1 version_ge_2 version_ge_a version_ge_b 
    # local version_ge_save_ifs 
    version_ge_v1="$1" 
    version_ge_v2="$2" 

    version_ge_save_ifs="$IFS" 
    while test -n "${version_ge_v1}${version_ge_v2}"; do 
     IFS="." 
     split "$version_ge_v1" version_ge_a version_ge_v1 
     split "$version_ge_v2" version_ge_b version_ge_v2 
     IFS="$version_ge_save_ifs" 
     #echo " compare $version_ge_a $version_ge_b" 
     test "0$version_ge_a" -gt "0$version_ge_b" && return 0 # v1>v2: true 
     test "0$version_ge_a" -lt "0$version_ge_b" && return 1 # v1<v2:false 
    done 
    # version strings are both empty & no differences found - must be equal. 
    return 0 # v1==v2: true 
} 
Problemi correlati