Bash: How to Print the Longest Line in a File


Often you may want to print the longest line in a file using Bash.

There are two common ways to do so:

Method 1: Print Contents of Longest Line in File

awk 'length > max_length { max_length = length; x = $0 } END { print x}' teams.txt

This particular example will print the contents of the longest line in the file named teams.txt.

Method 2: Print Length of Longest Line in File

awk 'length > max_length { max_length = length; x = length } END { print x}' teams.txt 

This particular example will print the length of the longest line in the file named teams.txt.

The following examples show how to use each of these methods in practice with a text file named teams.txt located in our current directory.

We can use the cat command to view the contents of this file:

The text file contains the names of various basketball teams.

Example 1: Print Contents of Longest Line in File

We can use the following syntax to print the contents of the longest line in the teams.txt file:

awk 'length > max_length { max_length = length; x = $0 } END { print x}' teams.txt

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

Bash print contents of longest line in file

The output returns Memphis Grizzlies, which represents the longest line in the teams.txt file.

Example 2: Print Length of Longest Line in File

We can use the following syntax to print the length of the longest line in the teams.txt file:

awk 'length > max_length { max_length = length; x = length } END { print x}' teams.txt

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

Bash print length of longest line in file

The output returns 17, which represents the length of the longest line in the teams.txt file.

Related Tutorials

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

Bash: How to Replace Text in String
Bash: How to Replace Special Characters in String
Bash: How to Replace Multiple Characters in String

Leave a Reply