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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 16:50:39  来源:igfitidea点击:

Bash - Sort a list of strings

bashlistsorting

提问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 sortprogram (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 sortcommand 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 '%s
list=(a z t b "item with spaces" c)

readarray -td '' sorted < <(printf '%s
select item in "${sorted[@]}"; do
    # do something
done
' "${list[@]}" | sort -z)
' "${list[@]}" | sort -z)

With bash 4.4you 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