Reputation: 805
I have a question when I use awk and grep to parse log files. The log file contains some strings with figures, e.g.
Amount: 20
Amount: 30.1
And I use grep to parse the lines with keyword "Amount", and then use awk to get the amount and do a sum:
the command is like:
cat mylog.log | grep Amount | awk -F 'Amount: ' '{sum+=$2}END{print sum}'
It works fine for me. However, sometimes the mylog.log file does not contains the keyword 'Amount'. In this case, I want to print 0, but the above awk command will print nothing. How can I make awk print something when grep returns nothing?
Upvotes: 0
Views: 1402
Reputation: 203625
If your line only contains "Amount: 20" then use @fedorqui's solution, but if it's more like "The quick brown fox had Amount: 20 bananas" then use:
awk -F'Amount:' 'NF==2{sum+=$2} END{print sum+0}' file
Upvotes: 2
Reputation: 174706
Awk one-liner,
awk -F 'Amount: ' '/Amount:/{print "1";sum+=$2}!/Amount:/{print "0"}END{print sum}' file
The above awk command would print the number 1 for the lines which has the string Amount
and it prints 0
for the lines which don't have the string Amount
. And also if the string Amount
is found on a line then it stores the value(column 2) to the sum
variable and adds it with any further values. Finally the value of the variable sum
is printed at the last.
Example:
$ cat file
Amount: 20
Amount: 30.1
foo bar
adbcksjc
sbcskcbks
cnskncsnc
$ awk -F 'Amount: ' '/Amount:/{print "1";sum+=$2}!/Amount:/{print "0"}END{print sum}' file
1
1
0
0
0
0
50.1
Upvotes: 1
Reputation: 289745
You can use this:
awk '/^Amount/ {amount+=$2} END {print amount+0}' file
With the +0
trick you make it print 0
in case the value is not set.
There is no need to grep + awk. awk alone can grep (and many more things!):
/^Amount/ {}
on lines starting with "Amount", perform what is in {}
.amount+=$2
add field 2's value to the counter "amount".END {print amount+0}
after processing the whole file, print the value of amount
. Doing +0
makes it print 0
if it wasn't set before.Note also there is no need to set 'Amount' as the field separator. It suffices with the default one (the space).
$ cat a
Amount: 20
Amount: 30.1
$ awk '/^Amount/ {amount+=$2} END {print amount+0}' a
50.1
$ cat b
hello
$ awk '/^Amount/ {amount+=$2} END {print amount+0}' b
0
Upvotes: 5