Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort string array in descending order in Bash?

Tags:

shell

sorting

let's say I have an array:

nameArr=("Leia", "Darth Vader", "Anakin", "Han Solo", "Yoda")

and I would like to sort in descending order. How could I do it in Bash shell scripting? In ascending order I am using command:

arrAsc=($(for l in ${nameArr[@]}; do echo $l; done | sort))

Thanks a lot for help!

like image 906
preneond Avatar asked Jul 02 '26 19:07

preneond


1 Answers

You can do so fairly easily making use of IFS (internal field separator), sort -r, and a little help from printf. Using command substitution you can output and sort the array and then simply read the sorted results back into nameArr. For instance:

#!/bin/bash

nameArr=("Leia", "Darth Vader", "Anakin", "Han Solo", "Yoda")

IFS=$'\n'           ## only word-split on '\n'
nameArr=( $(printf "%s\n" ${nameArr[@]} | sort -r ) )  ## reverse sort

declare -p nameArr  ## simply output the array

Example Use/Output

Calling the script results in the following:

$ bash revarr.sh
declare -a nameArr='([0]="Yoda" [1]="Leia," [2]="Han Solo," [3]="Darth Vader," [4]="Anakin,")'

note: don't forget to restore the default IFS=$' \t\n' (space, tab, newline) when done with the sort if your script continues.

like image 107
David C. Rankin Avatar answered Jul 05 '26 12:07

David C. Rankin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!