Welcome to OGeek Q&A 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 Reply

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[@]}"


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...