Tuesday, April 14, 2009

Find length of longest line - awk bash


This is how we can find the length of the longest line in a file.


$ awk ' { if ( length > L ) { L=length} }END{ print L}' file.txt

Output:
25


And also to print the longest line along with the length:


$ awk ' { if ( length > L ) { L=length ;s=$0 } }END{ print L,"\""s"\"" }' file.txt

Output:
25 "136068 sumAQSD.1236800000"


Read about awk built in string manipulation function length

3 comments:

kg23 said...

Output the length of the longest line in a file:
$ wc -L file.txt

Jadu Saikia said...

@kg23, thanks a lot for this. really helpful. never knew about this. thanks

-L, --max-line-length
print the length of the longest line

Mike said...

Note that some (if not many) implementations do not include the "-L" option for wc.

© Jadu Saikia www.UNIXCL.com