Sort a file based on length of the column/row

awkgrepsedsorttext processing

I need to sort a file based on the number of chars in the first column.

I have no idea on how to go about this. (On Linux, so sed/awk/sort is available).

An example:

.abs is bla bla 12
.abc is bla se 23 bla
.fe is bla bla bla
.jpg is pic extension
.se is for swedish domains

what I want is to sort these lines, based on the length of the first column in each line.
Some of the lines start with 4 characters, some start with 3, or 2. I want the result to be something like:

.fe is bla bla bla
.se is for swedish domains
.abs is bla bla 12
.abc is bla se 23 bla
.jpg is pic extension

Is this even possible?

Best Answer

You can first add another column with count of characters with awk, do sort and then strip added column:

awk '{printf "%d %s\n", length($1), $0}' file.txt | sort -n -k1,1 | sed -E -e 's/^[0-9]+ //'

Related Question