Shell tricks: sort a Bash array by length

[Tweet : ADN : nvALT]

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[@]}
l
s
sh
sho
short
loooooong

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 BrettTerpstra.com posts. Readers can get 10% off using the coupon code TERPSTRA.