Bash: How to Sort a File by Line Length


Often you may want to use Bash to sort the lines in a file based on line length.

The easiest way to do so is by using the Perl sort() function with the following syntax:

perl -e 'print sort { length($a) <=> length($b) } <>' phrases.txt

This particular example will sort the rows of the file named phrases.txt based on line length (including spaces) from shortest to longest.

If you’d like to sort from longest to shortest, simply swap the $a and $b in the code.

The following example shows how to use this syntax in practice.

Example: Use Bash to Sort a File by Line Length

Suppose that we have a text file named phrases.txt that contains various phrases:

Suppose that we would like to sort the rows based on line length from shortest to longest.

We can use the following syntax to do so:

perl -e 'print sort { length($a) <=> length($b) } <>' phrases.txt

The following screenshot shows how to use this syntax in practice:

Bash sort by line length

Notice that the rows are sorted by line length from shortest to longest.

If we would instead like to sort the rows based on line length from longest to shortest, we can swap the $a and the $b in the code:

perl -e 'print sort { length($b) <=> length($a) } <>' phrases.txt

The following screenshot shows how to use this syntax in practice:

Bash sort by line length from longest to shortest

Notice that the rows are now sorted by line length from longest to shortest .

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Sort File by Multiple Columns
Bash: How to Sort by Last Column in File
Bash: How to Count Number of Unique Lines in File

Leave a Reply