Bash - 对字符串列表进行排序

10

请问如何使用Bash对以下列表(或一般列表)进行排序(升序A到Z)?

我一直在尝试,但仍然无法得到期望的结果:

my_list='a z t b e c'

结果也应该是一个列表,因为我将在Select循环中使用它。
my_list='a b c e t z'  

感谢您的帮助!

4
你尝试了什么?展示一下你的尝试。 - Reut Sharabani
你需要将列表转换为字符串吗?难道不能使用数组吗? - PesaThe
@PesaThe 输入输出是列表。对于数组,我可以使用冒泡排序将其排序。 - Hung Tran
1
@HungTran 你也可以在 select 循环中使用数组,不必需要一个 “string” 列表。 - PesaThe
@lurker OP 很可能指的是 select 关键字。 - PesaThe
@lurker 和 @PesaThe,是的,这是Bash中的select循环 - Hung Tran
5个回答

16
您可以使用两次 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

8

如果允许使用 sort 程序(而不是在 bash 中编写排序算法),答案可能如下:

my_list='a z t b e c'
echo "$my_list" | tr ' ' '\n' | sort | tr '\n' ' '

结果为:a b c e t z'

5

数组更适合存储一系列事物:

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

1

使用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

0

你可以做到这件事

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接