KornShell整数排序数组 [英] KornShell Sort Array of Integers
问题描述
KornShell(ksh)脚本中是否有命令来对整数数组进行排序?在这种特定情况下,我对简单性而非效率感兴趣.例如,如果变量$ UNSORTED_ARR包含值"100911、111228、090822",而我想将结果存储在$ SORTED_ARR
Is there a command in KornShell (ksh) scripting to sort an array of integers? In this specific case, I am interested in simplicity over efficiency. For example if the variable $UNSORTED_ARR contained values "100911, 111228, 090822" and I wanted to store the result in $SORTED_ARR
推荐答案
它实际上是索引数组还是字符串列表?
Is it actually an indexed array or a list in a string?
数组:
UNSORTED_ARR=(100911 111228 090822)
SORTED_ARR=($(printf "%s\n" ${UNSORTED_ARR[@]} | sort -n))
字符串:
UNSORTED_ARR="100911, 111228, 090822"
SORTED_ARR=$(IFS=, printf "%s\n" ${UNSORTED_ARR[@]} | sort -n | sed ':a;$s/\n/,/g;N;ba')
还有其他几种方法可以做到这一点,但是原理是相同的.
There are several other ways to do this, but the principle is the same.
这是使用另一种技术的字符串的另一种方式:
Here's another way for a string using a different technique:
set -s -- ${UNSORTED_ARR//,}
SORTED_ARR=$@
SORTED_ARR=${SORTED_ARR// /, }
请注意,这是一种 lexicographic 排序方式,因此当数字没有前导零时,您会看到这种情况:
Note that this is a lexicographic sort so you would see this kind of thing when the numbers don't have leading zeros:
$ set -s -- 10 2 1 100 20
$ echo $@
1 10 100 2 20
这篇关于KornShell整数排序数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!