wesley tanaka

Finding the longest line in a file

‹ Paying your phone bill with a big stack of pennies | MySQL Database Table Schema for international geonames ›
()

One way to print out the number of characters in each line of a file:

awk '{print length, $0}'

One way to find the longest line is awk '{print length, $0}'|sort -nr|head -1. For example, to find the line with the maximum length in the file abcd.txt, (and how long that line is) you could run:

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

If you just want to know what the largest length is, you can remove the , $0 like so:

cat abcd.txt|awk '{print length}'|sort -nr|head -1

Thanks

I found this tip helpful.

You could also use wc -L

You could also use wc -L

you can't allways use wc -L

see $subject,

depending on the 'wc' you have you can or can't use the -L option
the awk method is preferable though as it also actually prints the line you're searching for.

a colleage of mine wrote a little scrit which actually finds the longest line, notice I had to use nawk
on a solaris box instead of the plain awk as it handles longer lines better :)

#!/bin/ksh
nawk 'BEGIN {longest=0} {
if ( length($0) > longest)
{
longest=length($0)
ll=$0
}}
END { print ll }' <$1

Great tip

Found this page on a google search and it was exactly what I was looking for.  Thanks!  I need to learn to use awk better.

Useless use of `cat' here.

Useless use of `cat' here. :-)

That is, it is preferrable to do:

 

awk '{print length, $0}' abcd.txt |sort -nr|head -1

 

Otherwise, wonderful.

 

cat allows you to use a pipe

The pipe is a more generic form - you may not always want to analyse a file, but output from a command for example.

Syndicate content
by Wesley Tanaka