Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 1 down vote accepted

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

Most command line tools work in a line-based manner, so to do this you first need to convert the wordlist into lines, this is easily done with tr ' ' '\n', which transliterates all spaces into new-lines. Then use the solution described here to sort by line length. Finally convert back to single line with paste.

echo 123 b 1 4rr f k3j3 gg   \
| tr ' ' '\n' < wordlist     \
| awk '{ print length, $0 }' \
| sort -n | cut -d' ' -f2    \
| paste -s -d ' '

Output:

1 b f gg 123 4rr k3j3

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.