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
  • 2
    Please clarify if you want to print the longest line from each file regardless of its line number or line number 2 from each file regardless of its length or something else. Your subject says Find and print the length of the longest line while your text says print all the file names with the length of the second line which elsewhere you say should be the longest so it's not clear what you want output if/when the 2nd line isnt the longest.
    – Ed Morton
    Mar 24, 2021 at 16:58
  • So for the work I am doing the longest line and the second line should be equal. I can explain if its necessary but its more biology/bioinformatics
    – Kevin
    Apr 7, 2021 at 15:23

3 Answers 3

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.


If the max line might not be line 2, you can do:

  • with GNU awk

    gawk '
        BEGINFILE {max = -1} 
        length > max {max = length} 
        ENDFILE {print FILENAME, max}
    ' *
  • with non-GNU awk

    awk '
        FNR == 1 {
            if (filename != "") print filename, max
            filename = FILENAME
            max = -1
        length > max {max = length}
        END {print filename, max}
    ' *
  • Could also print FNR to tell which line was longest. Or check it against the assumed 2 and scream if it's some other.
    – ilkkachu
    Mar 24, 2021 at 20:27

Normally the GNU wc should do the job.

wc -L A*
  • Assuming files don't choke the command line. In that scenario you can use a for loop or a find command.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .