Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

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?

share|improve this question

3 Answers 3

up vote 4 down vote accepted

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:

share|improve this answer
2  
@don.joey: that's the power of unix. Simple commands, that can work together. here, he looks for "^.{n}$", ie any line that, between the beginning of line (^) and its end ($) has exactly n characters (.{n}). Then he just needs to find n: for this he uses a GNU-ism, "wc -L filename" (note that this is not posix) which returns the length of the longest line of filename. So he greps any line that has the longest length. $(cmd) is replaced by the output of cmd. –  Olivier Dulac Nov 12 '13 at 16:26
1  
@OlivierDulac Great comment. –  Radu Rădeanu Nov 12 '13 at 16:27

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
share|improve this answer
    
@user214965 please see my update, the line number displayed is the second number in the result. –  Attila O. Nov 12 '13 at 9:57
    
What if there are 2 lines with the same maximum length? –  Radu Rădeanu Nov 12 '13 at 10:09
    
@RaduRădeanu good point. +1 for wc -L, I didn't know about that argument. It is very useful indeed. –  Attila O. Nov 12 '13 at 14:31

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
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.