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
2009-10-31 19:39:24
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
2009-10-31 22:17:49
+4
A:
cat filename|awk '{print length, $0}'|sort -nr|head -1
For reference : Finding the longest line in a file
Ravi
2009-10-31 20:13:45
Why the extra cat command? Just give the file name directly as an argument to awk.
Thomas Padron-McCarthy
2009-10-31 21:40:33
@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
2009-10-31 23:31:11
+2
A:
Here are references of the anwser
cat filename | awk '{print length, $0}'|sort -nr|head -1
Nadir SOUALEM
2009-10-31 20:56:39
+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
2009-10-31 21:38:14
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
2009-11-02 00:56:22
+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
2010-02-11 20:31:58