Shell Bash脚本以升序打印数字 [英] Shell Bash script to print numbers in ascending order
本文介绍了Shell Bash脚本以升序打印数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我真的是Shell Bash脚本的新手.对于用户输入的给定任意数字,我需要在一行上按升序打印数字.
I am really new to shell Bash scripting. I need to print numbers in ascending order on a line for a given arbitrary number that is input by the user.
#!/bin/bash
declare nos[5]=(4 -1 2 66 10)
# Prints the number befor sorting
echo "Original Numbers in array:"
for (( i = 0; i <= 4; i++ ))
do
echo ${nos[$i]}
done
#
# Now do the Sorting of numbers
#
for (( i = 0; i <= 4 ; i++ ))
do
for (( j = $i; j <= 4; j++ ))
do
if [ ${nos[$i]} -gt ${nos[$j]} ]; then
t=${nos[$i]}
nos[$i]=${nos[$j]}
nos[$j]=$t
fi
done
done
#
# Print the sorted number
#
echo -e "\nSorted Numbers in Ascending Order:"
for (( i=0; i <= 4; i++ ))
do
echo ${nos[$i]}
done
推荐答案
您可以使用以下脚本:
#!/bin/bash
IFS=' ' read -ra arr -p "Enter numbers: "
Enter numbers: 4 -1 2 66 10
sort -n <(printf "%s\n" "${arr[@]}")
-1
2
4
10
66
-
IFS =''
使read
的所有数字都由空格分隔 - 'read -ra`读取数组中的所有数字
-
sort -n
对数字进行数字排序 -
printf%s \ n""$ {arr [@]}"
可以在单独的行中打印数组的每个元素 -
<(printf%s \ n""$ {arr [@]}")
是进程替换,使printf
命令的行为类似于sort -n
命令. IFS=' '
to makeread
all number delimited by space- 'read -ra` to read all numbers in an array
sort -n
to sort numbers numericallyprintf "%s\n" "${arr[@]}"
to print each element of array in separate line<(printf "%s\n" "${arr[@]}")
is process substitution that make itprintf
command behave like a file forsort -n
command.
这篇关于Shell Bash脚本以升序打印数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文