10

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
muru
  • 193,181
  • 53
  • 473
  • 722
bambosze_babuni
  • 167
  • 1
  • 10

3 Answers3

17

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.

Thor
  • 3,513
  • 25
  • 27
  • tricky and cool! (+1) –  Mar 28 '17 at 10:32
  • 2
    If any or the lines is empty, the assignment evaluates to zero (a falsy value), and the length will not be printed. – ilkkachu Mar 28 '17 at 17:03
  • @ilkkachu: Depending on the situation, it would be reasonable to ignore empty lines. I have added a note about this. – Thor Mar 28 '17 at 19:02
14

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

awk 'NR <= 3 {print length}' /etc/passwd
  • 3
    If this was `awk '{ print length } NR>=3 { exit }' /etc/passwd`, I'd upvote it. – Dennis Williamson Mar 28 '17 at 18:08
  • 3
    @DennisWilliamson, thank you. That is a very good suggestion, I will not include it in my answer because it is already implicit in Thor's proposal. –  Mar 28 '17 at 18:28
5

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 
muru
  • 193,181
  • 53
  • 473
  • 722
Yaron
  • 12,828
  • 7
  • 42
  • 55