How to get longest line from a file?

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"

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

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