KornShell Sort Array of Integers

巧了我就是萌 提交于 2019-12-01 13:20:06

Is it actually an indexed array or a list in a string?

Array:

UNSORTED_ARR=(100911 111228 090822)
SORTED_ARR=($(printf "%s\n" ${UNSORTED_ARR[@]} | sort -n))

String:

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// /, }

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
nexus.christopher

If I take that out then it works but I can't loop through it (because its a list of strings now) – pws5068 Mar 4 '11 at 21:01

Do this:

\# create sorted array
set **-s** -A $@ 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!