Bash – Find and print the length of the longest line in multiple files

awkbashshell

In my folder, I have 2000 files, which are labeled A0001-A2000. In the second line of each file, there is a long (it should be the longest) line of characters. I would like to print all the file names with the length of the second line in one output.

so the output will look something like

A0001 231
A0002 123
A0003 56

If it is helpful I already have a code that will print the longest line of a file, but I am not tied to using awk if there is an easier way.

$ awk '{print length}' A0001.txt |sort -nr|head -1
231

Best Answer

awk 'FNR==2{print FILENAME,length; nextfile}' *

The glob expands to all files in the directory, and when Awk reaches the 2nd line it prints the filename and its length and skips to the next file. This nextfile is optional and for performance only.

If there may be non-regular files in the directory, use Find so that Awk does not choke:

find . -type f -maxdepth 1 -exec awk 'FNR==2{print FILENAME,length; nextfile}' {} +

-maxdepth 1 makes find non-recursive (i.e. it does not look into subdirectories). You can also use -prune if -maxdepth is not available.

Related Question