awk - How to print the number of characters for the first n lines in a file?

Solution 1:

Tell awk to quit when enough lines have been read:

awk '$0 = length; NR==3 { exit }' /etc/passwd

Note that this solution ignores empty lines, although not for the line count.

Solution 2:

A direct Awk version (not so efficient as @Thor's), but slightly more clear:

awk 'NR <= 3 {print length}' /etc/passwd

Solution 3:

You can execute it with awk only command, as nicely described by @Thor, and @JJoao (+1 from me)

You can combine awk and head with parameter -n follows by the number of lines as described below:

Thanks for @Maerlyn suggestion to execute in this order: head | awk

e.g. You will get the first 3 lines using:

head -n3 /etc/passwd | awk '{ print length($0); }' 

head man

-n, --lines=[-]K
    print the first K lines instead of the first 10; with the leading '-', print all but the last K lines of each file