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?

asked Jan 7, 2016 by anonymous

1 Answer

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 Jan 14, 2016 by Eric Z Ma (44,280 points)

Please log in or register to answer this question.

Copyright © SysTutorials. User contributions licensed under cc-wiki with attribution required.
Hosted on Dreamhost

...