bashsorting

Sort list by number of character AND alphabetical


Using bash I would like to sort a list of text strings in accordance with a first and a second order criteria:

  1. Number of characters in the text string; string with fewest characters first
  2. In order of the Danish alphabet which is the same as the English except for the letters æ, ø, å in the end (after z)

Example:

I would like this list:

aabb
ccc
aaaa
ddd
dgg
øøøø
aa
cc
ab

To be sorted into this:

aa
ab
cc
ccc
ddd
dgg
aaaa
aabb
øøøø

How can that be achieved?


Solution

  • With bash, sort and cut:

    while read -r l; do echo "${#l} $l"; done < filename | sort -n | cut -d " " -f 2-
    

    Output:

    aa
    ab
    cc
    ccc
    ddd
    dgg
    aaaa
    aabb
    øøøø
    

    Replace filename in the middle of the command.