I'm looking for the simplest method to print the longest line in a file. I did some googling and surprisingly couldn't seem to find an answer. I frequently print the length of the longest line in a file, but I don't know how to actually print the longest line. Can anyone provide a solution to print the longest line in a file? Thanks in advance.
UPD: summarizing all the advices in the comments
This first reads the file inside the command substitution and outputs the length of the longest line, (previously,
Another, I had thought earlier than the sed one (in bash):
In pure bash:
The following example was going to be, and should have been, a comment to dmitry.malikov's answer, but because of the Useless Use of Visible Comment Space there, I've chosen to present it here, where it will at least be seen...
This is a simple variation of the dmitry's
single-pass awk method.
Here's a Perl solution:
Or, if you want to print all the longest lines
Since I had nothing better to do, I ran some benchmarks on a 625M text file. Surprisingly, my Perl solution was consistently faster than the others. Granted, the difference with the accepted
Print only one of the longest lines:
Print all longest lines :
Grep the first longest line
The command is unusually hard to read without practise because it mixes shell- and regexp syntax.
How it works
The command has two parts, a
Here, the process expansion was replaced with the value it would return, creating the
Which longest lines?
To make the examples more readable with the filename occurring twice, I will use a variable
Show the first longest line - the first line that is as long as the longest line:
Show all longest lines - all lines that are as long as the longest line:
Show the last longest line - the last line that is as long as the longest line:
Show the single longest line - the longest line longer than all other lines, or fail:
(The last command is even more inefficient than the others, as it repeats the complete grep command. It should obviously be decomposed so that the output of