How to get longest line from a file?

I'm interested to find out the line number of the longest line from a file.

For example, if I have a file with the following content:

lalala
tatatata
abracadabra
mu mu mu

how can I write a bash script that will give me an output something like this: 3 -> abracadabra?


Solution 1:

You don't need a script for doing this. A simple command is enough:

egrep -n "^.{$(wc -L < filename)}$" filename

This will work even when you have two or more lines with the same maximum length.

If you want that the output to be exactly in this form: 3 -> abracadabra, then use:

egrep -n "^.{$(wc -L < filename)}$" filename | sed 's/:/ -> /'

References:

  • Longest line in a file
  • Find the line number where a specific word appears with "grep"

Solution 2:

You could use awk to print the length of each line (length()) and the line number (NR), then reverse (-r) sort the result by number (-n):

$ awk '{ print length(), NR, $0 | "sort -rn" }' tmp.txt
10 3 abracadabr
8 4 mu mu mu
7 2 tatatat
6 1 lalala

To show just the first line:

$ awk '{ print length(), NR, $0 | "sort -rn" }' tmp.txt | head -n 1
10 3 abracadabr

Solution 3:

A O(N) can be achieved with a perl one liner :

perl -e 'while (<>) { if (length > length $max) { $max=$_}}; print $max'

usages (where machin is a file name)

cat machin | perl -e 'while (<>) { if (length > length $max) { $max=$_}}; print $max'

or

perl -e 'while (<>) { if (length > length $max) { $max=$_}}; print $max' machin

or (less clear but shorter)

perl -ne 'if(length>length$m){$m=$_};END{print$m}' machin