sgeza
sgeza

Reputation: 361

Adding rows in awk-output

I'm using awk to write a bash script that outputs the count of error codes ranging from 400 - 500 that appear in a text file called output.txt

awk '($9 >= 400)' output.txt | awk '{print $9}' | sort | uniq -c

The output of the above is:

  12 400
  11 401
  55 403
  91 404
  41 500

How do I add the first column together using bash so that in the example above, I get 210 instead of the above output... (12 + 11 + 55 + 91 + 41 = 210)

And if I wanted to input in a file via command line argument instead of output.txt how should I edit the script? I know that you use '$1' and '$2' to access command line arguments, but in this case how would it work considering I'm already using $9 in with awk

Upvotes: 1

Views: 293

Answers (2)

Ed Morton
Ed Morton

Reputation: 203684

To get the count of error codes ranging from 400 - 500 that appear in a text file called output.txt assuming each error code is in $9 is:

awk '($9 >= 400) && ($9 <= 500) && !seen[$9]++{cnt++} END{print cnt+0}' output.txt

To get the count of **lines containing** error codes ranging from 400 - 500 that appear in a text file called output.txt assuming each error code is in $9 is:

awk '($9 >= 400) && ($9 <= 500){cnt++} END{print cnt+0}' output.txt

Upvotes: 1

RavinderSingh13
RavinderSingh13

Reputation: 133538

To fix your problem immediate since you are using already 1 command, could try as(though I am pretty sure if you could share sample of your input we could probably do it in a single command too):

your_command | awk '{sum+=$1} END{print sum}'

Also in OP's command part awk '($9 >= 400)' output.txt | awk '{print $9}' could be shorten to awk '($9 >= 400){print $9}' output.txt

Upvotes: 3

Related Questions