views:

677

answers:

8

I'm looking for a simple way to find the longest line in a file. Ideally, it would be a simple bash shell command instead of a script.

+10  A: 
awk '{ if (length($0) > max) {max = length($0); maxline = $0} } END { print maxline }'  YOURFILE
Ramon
The example was taken from the awk manual (imagine that!) and modified to print the actual line instead of the length of the longest line.
Ramon
+4  A: 
cat filename|awk '{print length, $0}'|sort -nr|head -1

For reference : Finding the longest line in a file

Ravi
Why the extra cat command? Just give the file name directly as an argument to awk.
Thomas Padron-McCarthy
@Thomas. Expressing it as a pipe is more general than specifying a file as an option. In my case, I'll be using output piped from a database query.
drewster
+2  A: 

Here are references of the anwser

cat filename | awk '{print length, $0}'|sort -nr|head -1

http://wtanaka.com/node/7719

Nadir SOUALEM
That second awk script will only tell you the longest length, not show the longest line.
rsp
Come on..These are same as the first two answers added with the references.
Ravi
I just add references
Nadir SOUALEM
@rsp: i kill the second anwser
Nadir SOUALEM
+1  A: 

In perl:

perl -ne 'print ($l = $_) if (length > length($l));' filename | tail -1

this only prints the line, not its length too.

rsp
A: 

Variation on the theme.

This one will show all lines having the length of the longest line found in the file, retaining the order they appear in the source.

FILE=myfile grep `tr -c "\n" "." < $FILE | sort | tail -1` $FILE

So myfile

x
mn
xyz
123
abc

will give

xyz
123
abc
martin clayton
+1  A: 

Just for fun, here's the Powershell version:

cat filename.txt | sort length | select -last 1

And to just get the length:

(cat filename.txt | sort length | select -last 1).Length
eddiegroves
+1  A: 

Using wc (GNU coreutils) 7.4:

wc -L filename

gives:

101 filename
Daniel
+1  A: 
wc -L < filename

gives

101
Anonymous