请问如何使用Bash对以下列表(或一般列表)进行排序(升序A到Z)?
我一直在尝试,但仍然无法得到期望的结果:
my_list='a z t b e c'
结果也应该是一个列表,因为我将在Select循环中使用它。
my_list='a b c e t z'
感谢您的帮助!
$ my_list='a z t b e c'
$ my_list=$(echo $my_list | xargs -n1 | sort | xargs)
$ echo $my_list
a b c e t z
如果允许使用 sort
程序(而不是在 bash
中编写排序算法),答案可能如下:
my_list='a z t b e c'
echo "$my_list" | tr ' ' '\n' | sort | tr '\n' ' '
a b c e t z'
。数组更适合存储一系列事物:
list=(a z t b "item with spaces" c)
sorted=()
while IFS= read -rd '' item; do
sorted+=("$item")
done < <(printf '%s\0' "${list[@]}" | sort -z)
使用 bash 4.4
版本,您可以使用 readarray -d
命令:
list=(a z t b "item with spaces" c)
readarray -td '' sorted < <(printf '%s\0' "${list[@]}" | sort -z)
select
的简单菜单:select item in "${sorted[@]}"; do
# do something
done
使用GNU awk和 PROCINFO["sorted_in"]
控制数组遍历顺序:
$ echo -n $my_list |
awk 'BEGIN {
RS=ORS=" " # space as record seaparator
PROCINFO["sorted_in"]="@val_str_asc" # array value used as order
}
{
a[NR]=$0 # hash on NR to a
}
END {
for(i in a) # in given order
print a[i] # output values in a
print "\n" # happy ending
}'
a b c e t z
你可以做到这件事
my_list=($(sort < <(echo 'a z t b e c'|tr ' ' '\n') | tr '\n' ' ' | sed 's/ $//\
'))
my_list
的数组。array =($(...anything ...))
不是很好的做法。参见[BashPitfalls#50](https://mywiki.wooledge.org/BashPitfalls#hosts.3D.28_.24.28aws_.2BICY.29_.29)。 - Charles Duffy
select
循环中使用数组,不必需要一个 “string” 列表。 - PesaTheselect
关键字。 - PesaTheselect循环
。 - Hung Tran