我一直在尝试从Bash中读取终端的数字输入(两种单独的方法。首先是直接在CLI中输入数字,然后从文件中读取数字)并将其保存在数组中,对数组进行排序并显示结果。 (最初的问题表明输入保存在数组中,然后进行排序)
我不知道将其保存在文件中并对文件中的值进行排序,还是直接将来自终端的输入排序到数组中,然后对其进行排序,是否更好。我已经搜索了这两种方法。
谢谢。
P.S。我已经阅读了许多资源和链接,但是不幸的是我找不到解决方案。我尝试使用循环并提示用户询问他们要输入多少个数字作为输入,但注定会失败。
无论哪种方式,您似乎都希望输入有限数量的输入,然后需要对其进行排序。只需将输入输入到sort -n
中即可(-n
用于数字排序)。无需使用中间数组。
# Print some numbers on the console, pipe into sort.
cat <<-EOF | sort -n
1
3
2
EOF
如果您的输入来自文件:
# Create FILE holding unsorted numbers. $ cat <<-EOF > FILE 1 3 2 EOF # Sort contents of FILE. $ cat FILE | sort -n 1 2 3
如果您更具体,将更容易提供帮助。
if [[ -t 0 ]]; then
# This line is executed when input from the terminal.
echo "Input a numeric value and enter then continue. Enter a blank line when done."
fi
while read -r n; do
[[ -z $n ]] && break # exits the loop if the input is empty
ary+=("$n")
done
sorted=($(sort -n < <(printf "%s\n" "${ary[@]}")))
printf "%s\n" "${sorted[@]}"
ary
按输入顺序保存值。sorted
保存排序的结果。