Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

need shell script to sort numbers including decimal numbers


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

i want the list to be as follow: -20 1.2 8 10 100

  1. Output numbers one per line.
  2. Sort
  3. Join with space

$ arr=(10 8 -20 100 1.2)
$ printf "%s
" "${arr[@]}" | sort -g | paste -sd' '
-20 1.2 8 10 100

Don't reimplement sort using shell - it's going to be incredibly slow. The -g option to sort may not be available everywhere - it's for sorting floating point numbers.

[: 1.2: integer expression expected Array

The [ command handles integers only. 1.2 has a comma, [ can't handle it. Use another tool. Preferable python.

${arr[$((j+1))]}

No need to use $(( - stuff inside [ is already expanded arithmetically. Just ${arr[j+1]}.

j<5-i-1

is strange condition. When i=4 then it's j<0 and loop will not run at all. Just iterate from i instead of up to i - ((j=i;j<5;++j)).

echo "Array in sorted order :" echo ${arr[*]}

Will print echo to output. Just echo "Array in sorted order : ${arr[*]}" or echo "Array in sorted order :" "${arr[@]}"


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...