12

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?

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.

my_list='a b c e t z'  

Thanks for your help!

6
  • 4
    What have you been trying? Show your attempts. Commented Feb 27, 2018 at 11:58
  • Do you need the list to be a string? Can't you use arrays? Commented Feb 27, 2018 at 12:09
  • @PesaThe The input output are lists. For an array, I can get it sorted with Bubblesort. Commented Feb 27, 2018 at 12:12
  • 1
    @HungTran You can use arrays for select loop as well. You don't need a "string" list. Commented Feb 27, 2018 at 12:15
  • @lurker OP most likely means the select keyword. Commented Feb 27, 2018 at 12:27

5 Answers 5

21

You can use xargs twice along with a built in sort command to accomplish this.

$ 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
Sign up to request clarification or add additional context in comments.

Comments

10

If you permit using the sort program (rather than program a sorting algorithm in bash) the answer could be like this:

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

The result: a b c e t z'

Comments

6

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\0' "${list[@]}" | sort -z)

With bash 4.4 you can utilize readarray -d:

list=(a z t b "item with spaces" c)

readarray -td '' sorted < <(printf '%s\0' "${list[@]}" | sort -z)

To use the array to create a simple menu with select:

select item in "${sorted[@]}"; do
    # do something
done

Comments

2

Using GNU awk and controling array traversal order with 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

Comments

0

You can do this

my_list=($(sort < <(echo 'a z t b e c'|tr ' ' '\n') | tr '\n' ' ' | sed 's/ $//\
'))

This will create my_list which is an array.

1 Comment

Note that array=( $(...anything...) ) is not great practice; see BashPitfalls #50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.