Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I know how to get length of the longest line in a text file with awk

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

but how can I get the length of the longest line of all files in a directory?

share|improve this question

3 Answers 3

up vote 6 down vote accepted

The most straightforward solution is to concatenate all the files and pipe the result to your script:

cat ./* | awk '{ if ( length > L ) { L=length} }END{ print L}'

You can also pass directly several files to awk:

awk '{ if ( length > L ) { L=length} }END{ print L}' ./*

Of course, there can be some warnings if files are in fact directories but it should be harmless. You may have bigger problems with binary files because they don't have a concept of line. So, in order to be more specific, you can do something like

 awk '{ if ( length > L ) { L=length} }END{ print L}' ./*.txt

to match only the .txt files in the current directory.

And, as @G-Man stated in his comment, * won't match hidden files (starting with a dot). If you want those, use * .*.

share|improve this answer
    
Or, arguably, cat * .* | .... Or eliminate the useless use of cat and say awk '...' * .*. –  G-Man Aug 18 at 15:07
    
@G-Man Indeed. I was editing my answer about that when you commented. :-) I said most straightforward because concatenating the files with cat is what seemed simpler at first. –  lgeorget Aug 18 at 15:09
    
Thanks, that worked! –  trupty Aug 18 at 15:51

If you want the max length per file, with GNU awk:

find . -type f -exec awk '
   length>l {l=length} ENDFILE{print FILENAME ":", +l; l=0}' {} +

Or the one max length in all the files:

find . -type f -exec cat {} + | awk 'length>l {l=length}; END{print +l}'

That assumes the files end in newline characters. If one file doesn't end in a newline character, then its last non-delimited line will be merged with the first line of the next file and possibly void your result.

share|improve this answer
    
They're text files, so they do end in newline characters (unless empty). –  Gilles Aug 18 at 21:14

With GNU wc:

cat *.txt|wc -L

-L prints the length of the longest line.

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.