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?
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?
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 * .*
.
If you want the max length per file, with GNU awk:
find . -type f -exec awk -v l=0 '
length>l {l=length} ENDFILE{print FILENAME ":", l; l=0}' {} +
Or the one max length in all the files:
find . -type f -size +1c -exec cat {} + |
awk -v l=0 '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.
-size +1c
is an optimisation as text files that are empty or contain only one character have respectively 0 line and 1 empty line, so won't have the longest line.
With GNU wc
:
cat *.txt|wc -L
-L
prints the length of the longest line.
-L
option is horrible, it counts single tabs as being 8 bytes each
– Harold Fischer
Mar 25 '20 at 01:49
Also with GNU wc (coreutils 8.4), it can handle multiple files
wc -L *.txt
wc -L
does, but your solution has the disadvantage that you have to wade through the max-length of all the other files first. Is there any advantage in that?
– Anthon
Feb 13 '15 at 15:05
cat * .* | ...
. Or eliminate the useless use of cat and sayawk '...' * .*
. – G-Man Says 'Reinstate Monica' Aug 18 '14 at 15:07awk '{ if ( length > L ) { L=length ;s=$0 } }END{ print L,"\""s"\"" }' **/*.txt
– python_kaa Aug 10 '21 at 17:02