How do I sort a wordlist by string length?

There is a wordlist look like this;

123
b
1
4rr
f
k3j3
gg

Then I needed to sort these words by string length (doesn't matter which start with numeric or string both are okay)

The output should be this:

b
1
f
gg
123
4rr
4rr

Is there a sort command that allows me to do this?


I assume you want to do this on the command-line.

Most command line tools work in a line-based manner, so it is straightforward with awk, sort and cut, see for example this other question:

awk '{ print length, $0 }' testfile | sort -n | cut -d" " -f2-

Breakdown:

# Print line-length and the line
awk '{ print length, $0 }' testfile |

# Sort numerically by line-length
sort -n |

# Remove line-length number
cut -d' ' -f2-

Output:

1
b
f
gg
123
4rr
k3j3

See man awk, info sort and info cut for more.