8

How can I use awk to count the total number of input lines in a file?

  • 1
    It's worth you putting some detail each time about what you've tried so far. Otherwise people might look at your previous questions and just think you're getting your homework done for you ;-) https://unix.stackexchange.com/users/221298/tcsasyla – steve Apr 30 '17 at 17:17

2 Answers2

27

The special variable NR holds the current line number. Once the entire file has been processed, it will hold the total number of lines of that file. So, you can do:

awk 'END{print NR}' file

Of course, that is a bit silly when there's a program designed specifically for this:

wc -l file
terdon
  • 242,166
  • 1
    Not silly to avoid wc because date $'+%Y\n%m\n%d'>file; wc -l file outputs > 3 file. (with the spaces on macOS/BSD, without them on GNU). if you are going to have to awk the integer out anyway… – Bruno Bronosky Sep 28 '20 at 21:28
  • 1
    @BrunoBronosky try wc -l < file instead. Or cat file | wc -l. – terdon Sep 29 '20 at 07:55
  • 1
    That works for GNU, but on macOS/BSD, the spaces are still there. echo "#$(date $'+%Y\n%m\n%d' | wc -l)#" returns # 3# #SMH – Bruno Bronosky Sep 29 '20 at 13:00
  • @BrunoBronosky huh. Thanks, I didn't realize that wasn't portable behavior. – terdon Sep 29 '20 at 13:06
  • 1
    wc -l counts the number of NEWLINE characters, not necessarily the number of lines. I prefer awk – Kajukenbo May 05 '22 at 19:45
  • @Kajukenbo lines are defined by newline characters, how else? Counting the number of lines means counting the number of newline characters. – terdon May 05 '22 at 20:07
  • @terdon It is not unheard of to have a line of text without a NL at the end. That is one reason many old-school Unix peeps say to be sure to have a Blank Line at the end of a file (like old /etc/hosts). That ensures there is NL at the end of the last "text" line. – Kajukenbo May 05 '22 at 21:34
  • @Kajukenbo if it doesn't have a newline, it isn't a line. They say you need to leave a blank line at the end because that's the POSIX definition of a text file. – terdon May 06 '22 at 07:44
  • Some of awk versions like Solaris one have record too long Error use gawk instead. – EsmaeelE Sep 19 '23 at 07:01
3

To count the total number of input lines in a file with awk:

awk 'END{ print NR }' input.data

Or with sed:

sed -n \$= input.data