开发者

KornShell Sort Array of Integers

开发者 https://www.devze.com 2023-02-15 01:40 出处:网络
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 con开发者_运

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 con开发者_运维知识库tained 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?

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


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

精彩评论

暂无评论...
验证码 换一张
取 消