Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question

migrated from serverfault.com Jan 31 '13 at 22:14

This question came from our site for professional system and network administrators.

2 Answers 2

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]+ //'

share|improve this answer

You can do it with basic shell tools, but if Perl is available, you can express your requirement more directly:

perl -l -e 'print sort {@a = split(/ /, $a, 2); @b = split(/ /, $b, 2);
                        length($a[0]) <=> length($b[0])} <>'

With the Schwartzian transform (more efficient for large input):

perl -l -e 'print map {$_->[0]}
                  sort {length($a->[1]) cmp length($b->[1])}
                  map {[$_, split(/ /, $_, 2)]} <>'

If you have Python, the code is more verbose but a bit clearer:

python -c 'import sys;
lines = sys.stdin.readlines();
lines.sort(key=lambda line: len(line.split()[0]));
share|improve this answer

Your Answer


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