Sort words based on word count on each line

Hi Folks :slight_smile:

I have a .txt file with thousands of words. I'm trying to sort the lines in order based on number of words per line.

Example

from:

word
word word word
word word
word word word word
word
word word word
word word

to desired output:

word
word
word word
word word
word word word
word word word
word word word word

Any help would be greatly appreciated.
Thanks for your help!

ps. Hope i posted this in the correct forum board. My apologies if it's in the wrong section

Assuming you don't have more than 99,999 words on a line and that words are separated by sequences of one or more blanks, the following should work:

#!/bin/ksh
awk '{printf("%05d%s\n", NF, $0)}' file.txt|sort|awk '{print substr($0, 6)}'
1 Like

Thank you Don! It works perfectly. Just what I needed. Many Thanks