Shell tricks: sort a Bash array by length

I’m certain there’s a more elegant way to do this, but I couldn’t find it. I needed to sort a Bash array of strings by the length of each element without getting too verbose. Here’s what I came out with:

declare -a arr=( s sho sh short l loooooong )
IFS=$'\n' GLOBIGNORE='*' sorted_arr=($(printf '%s\n' ${arr[@]} | awk '{ print length($0) " " $0; }' | sort -n | cut -d ' ' -f 2-))

Now the sorted_arr variable contains an array of elements from arr sorted by line length in ascending order:

$ echo ${sorted_arr[@]}
l s sh sho short loooooong

$ printf '%s\n' ${sorted_arr[@]}

If you want to reverse the order, just change the sort -n section of the oneliner to sort -r -n (reverse).

By the way, this is from a quick change I made to Reiki (v1.1.3 is up) that allows it to assume that the shortest match is the most likely when testing multiple fuzzy matches. Just in case you cared…

Ryan Irelan has produced a series of shell trick videos based on posts. Readers can get 10% off using the coupon code TERPSTRA.

Brett Terpstra

Brett is a writer and developer living in Minnesota, USA. You can follow him as ttscoff on Twitter, GitHub, and Mastodon. Keep up with this blog by subscribing in your favorite news reader.

This content is supported by readers like you.

Join the conversation