Note that this solution does not perform well on large input.
You could also do the sorting within awk
:
cat << EOF > file
This is a long sentence.
This is not so long.
This is not long.
EOF
sort.awk
# Only find length once
{ len = length($0) }
# If we haven't seen this line before add it to the lines array
# and move on to next record
lines[len] == "" { lines[len] = $0; next }
# A duplicate, append to the previous record
{ lines[len] = lines[len] RS $0 }
END {
# lines array is sorted according to the indices, the sorted
# indices are stored in the indices array
asorti(lines, indices)
for(key in indices)
print lines[indices[key]]
}
Run like this:
awk -f sort.awk file
Or as a one-liner:
< file awk '{ len = length($0) } lines[len] == "" { lines[len] = $0; next } { lines[len] = lines[len] RS $0 } END { asorti(lines, indices); for(key in indices) print lines[indices[key]] }'
Output:
This is not long.
This is not so long.
This is a long sentence.