Ubuntu – awk – How to print the number of characters for the first n lines in a file

awkcommand linetext processing

I have a command:

$ awk '{ print length($0); }' /etc/passwd

It prints number of characters of every line in a passwd file:

52
52
61
48
81
58
etc.

How can I print the number of characters for only the first n lines?

For example – for the first 3 lines it would give something like:

52
52
61

Best Answer

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.