0

I'm having issues with displaying the row count displayed from a script I am currently working on and I am using Putty. This script reads a text file that looks similar to

user1|login|1
user2|login|1
user1|testing tests|10
user1|voiding tests|10
user2|logout|1
user1|logout|1

Currently my awk looks like

awk -F '|' '$1 == "user1" {sum += $3} END {print "user has run " NF "
processes for a total of "  sum " minutes" }' textfile

Currently this is supplying me with "user1 has run 3 process for a total of 22 minutes"

I need it to properly count the rows which should be four if my math is correct.

0

NF is the "number of fields", i.e. the number of columns. In this case, each line has 3 columns, hence the output is always 3, regardless of the number of matches. You need to have an additional count for each match encountered, i.e. proc below.

$ awk -F '|' '$1 == "user1" {proc += 1; sum += $3} END {print "user has run " proc " processes for a total of "  sum " minutes" }' textfile
user has run 4 processes for a total of 22 minutes
  • Yeah, this cleared it up. Not sure why I was fixated on NF and didn't think of adding another count... Thanks a bunch! – SoggyJ Dec 4 '18 at 21:58
  • For clarification: NF in the END section , if defined at all, has the field count of the last line. – RudiC Dec 4 '18 at 22:11
0

For the given example, try:

Just for one user:

awk -F'|' '$1=="user1"{i=$1;u[$1]++;m[$1]+=$3};END{print i,"processes:",u[i],"minutes:",m[i]}' file1
user1 processes: 4 minutes: 22

For all users:

awk -F'|' '++u[$1]{m[$1]+=$3};END{for (i in u) print i,"processes:",u[i],"minutes:",m[i]}' file1
user1 processes: 4 minutes: 22
user2 processes: 2 minutes: 2
-1

The problem is that NF is not the number of lines that were matched but the number of fields (columns). You could, for example, define another variable similar to "sum" and use that to count.

  • You mean, like my answer that I posted 5 minutes before this one? – Sparhawk Dec 4 '18 at 21:54
  • Congratulations for being faster. Your answer was not there yet when I started writing mine. – WerKater Dec 5 '18 at 8:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.