Search code examples
bashshellsorting

How to sort numbers into 1,2,3,4,...,22 instead of 1,10,11,..,2,20,21,22 in script shell?


Right now i have

listOfFiles = a list of array name like version1, version2,..,version22 // originally sql file
FILES=()
for s in $listOfFiles; 
do FILES+=($s);
done
# sort the array into ascending order
Sorted=($(echo ${FILES[*]}| tr " " "\n" | sort -n))
for s in "${Sorted[@]}";
# check existing script files version
do  a=$(tr -cd 0-9 <<<"$s");   
if [ $a -gt $formerVersion ]; 
    then $(mysql ...//execute the sql); 

which executes in order of version1,version10,version11,..,version2,version20,version21,version22, not version1,version2,version3,...version22 as expected


Solution

  • Soleve it by using:

    sort -n -k 2 -t n
    

    Reference page: https://www.computerhope.com/unix/usort.htm