How to sort lines by length in Linux?

I have a text file with many lines of text.

In Linux, how to sort the lines by their length?

You can make use of awk together with the sort program like

awk '{ print length(), $0 | "sort -n" }' /path/to/text/file

Here, we use awk to calculate the text length and sort -n to sort by the length as numbers.

If you want the original text only, you may use cut or awk again to filter away the leading number for the length.

Answered by Eric Z Ma.

Eric Z Ma

Eric is a father and systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

Leave a Reply

Your email address will not be published. Required fields are marked *