Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort a file based on length of chars in the first column/row

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. I'm using Linux, so sed/awk/sort are all available.

.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?

like image 540
Instronics Avatar asked Dec 11 '22 18:12

Instronics


1 Answers

Augment each line by the length of the first word, then sort:

awk '{ print length($1) " " $0; }' $FILE | sort -n

If necessary, cut out the helper field with cut -d ' ' -f 2- afterwards.

like image 78
thiton Avatar answered Mar 23 '23 16:03

thiton