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 :
|
|||
|
|
|
You can use
|
|||||
|