Sample Header Ad - 728x90

Bash sort array according to length of elements?

12 votes
7 answers
6406 views
Given an array of strings, I would like to sort the array according to the length of each element. For example... array=( "tiny string" "the longest string in the list" "middle string" "medium string" "also a medium string" "short string" ) Should sort to... "the longest string in the list" "also a medium string" "medium string" "middle string" "short string" "tiny string" (As a bonus, it would be nice if the list sorted strings of the same length, alphabetically. In the above example medium string was sorted before middle string even though they are the same length. But that's not a "hard" requirement, if it over complicates the solution). It is OK if the array is sorted in-place (i.e. "array" is modified) or if a new sorted array is created.
Asked by Enterprise (259 rep)
Nov 17, 2018, 08:11 PM
Last activity: Nov 27, 2024, 09:05 AM