Bash - 对字符串列表进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49008137/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bash - Sort a list of strings
提问by Hung Tran
Would you please show me know how I can sort the following list (ascending oder A to Z) (or a list in general) with Bash?
请告诉我如何使用 Bash 对以下列表(从 A 到 Z 升序)(或一般列表)进行排序?
I have been trying but still could not get the expected results:
我一直在尝试,但仍然无法得到预期的结果:
my_list='a z t b e c'
And the result should be a list as well, as I will use it for Select Loop.
结果也应该是一个列表,因为我将它用于 Select Loop。
my_list='a b c e t z'
Thanks for your help!
谢谢你的帮助!
回答by Renardo
If you permit using the sort
program (rather than program a sorting algorithm in bash
) the answer could be like this:
如果您允许使用该sort
程序(而不是在 中编写排序算法bash
),则答案可能如下所示:
my_list='a z t b e c'
echo "$my_list" | tr ' ' '\n' | sort | tr '\n' ' '
The result: a b c e t z'
结果: a b c e t z'
回答by Alex Stiff
You can use xargs twice along with a built in sort
command to accomplish this.
您可以将 xargs 与内置sort
命令一起使用两次来完成此操作。
$ 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
回答by PesaThe
Arrays are more suitable to store a list of things:
数组更适合存储事物列表:
list=(a z t b "item with spaces" c)
sorted=()
while IFS= read -rd '' item; do
sorted+=("$item")
done < <(printf '%slist=(a z t b "item with spaces" c)
readarray -td '' sorted < <(printf '%sselect item in "${sorted[@]}"; do
# do something
done
' "${list[@]}" | sort -z)
' "${list[@]}" | sort -z)
With bash 4.4
you can utilize readarray -d
:
有了bash 4.4
你可以利用readarray -d
:
$ 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]=##代码## # 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
To use the array to create a simple menu with select
:
要使用数组创建一个简单的菜单select
:
回答by James Brown
Using GNU awk and controling array traversal order with PROCINFO["sorted_in"]
:
使用 GNU awk 并通过以下方式控制数组遍历顺序PROCINFO["sorted_in"]
: