You can get a list of all line numbers one per line ordered first by length and second by line number starting w/ the largest like...
</path/to/infile LC_ALL=C \ tr -c \\n 1|grep -n '.\|'|sort -t: -rnk2
The method is very simple - tr
converts every input byte which is not a \n
ewline character to a 1, grep -n
prepends each line's number then a :
to all lines in its input, which sort
then sorts in reverse numeric order from the 2cd field through the tail of the line as delimited by a :
. So the longest string of 1s floats to the top.
You should beware, though, that if the input includes multibyte characters then this will number only by byte - not by character. To do the latter thing robustly is not a minor undertaking (as I understand it).
In any case - in an ASCII locale - the above should be very fast even for very large inputs. And it requires very little else to be a complete solution:
f=/path/to/file n=$(<"$f" tr -c \\n 1|grep -n '.\|'|sort -t: -rnk2|head -n1) l=$(<"$f" head -n"${n%:*}"|tail -n1) printf "Line #%s at #${#l} bytes. Its contents:\n%s\n" \ "${n%:*} is (possibly tied-for) the longest in $f" "$l"