KornShell Sort Array of Integers

拈花ヽ惹草 提交于 2019-12-19 10:57:52

问题


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


回答1:


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



回答2:


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 $@ 


来源:https://stackoverflow.com/questions/5198283/kornshell-sort-array-of-integers

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