1

I have a file called file.csv with multiple rows and columns like this:

API,20042017-01:00,341701,341701,480692,480692
API,20042017-02:00,293058,293058,415459,415459
API,20042017-03:00,272692,272692,388942,388942
API,20042017-04:00,279117,279115,399361,399361
API,20042017-05:00,345947,345945,495306,495306

and I want to calculate the percent value by multiplying the ratio of column 4 to column 3 by 100, so I typed in the following command:

awk -F, '{ print $1, $2, $3, $4, ($4/$3*100), $5, $6 }' file.csv

which gives me the required output:

API,20042017-01:00,341701,341701,100,480692,480692
API,20042017-02:00,293058,293058,100,415459,415459
API,20042017-03:00,272692,272692,100,388942,388942
API,20042017-04:00,279117,279115,100,399361,399361
API,20042017-05:00,345947,345945,100,495306,495306

but when there's a non integer in column 3, it gives me a error saying:

awk: (FILENAME=file.csv FNR=3) fatal: division by zero attempted

and stops counting the rest of the rows.

How could I make it continue?

0

You can ask awk to validate if a field is a number by using ~ /^[0-9]+/.

Here's a little shell script that demonstrates this:

[root@tiny ~]# cat test.sh
#!/bin/bash

INPUT="API,20042017-01:00,341701,341701,100,480692,480692
API,20042017-02:00,293058,293058,100,415459,415459
API,20042017-03:00,272692,272692,100,388942,388942
API,20042017-04:00,279117,279115,100,399361,399361
API,20042017-04:00,279117,FRED,100,399361,399361
API,20042017-05:00,345947,345945,100,495306,495306"

echo "$INPUT" | awk -F, '$3 ~ /^[0-9]+/ && $4  ~ /^[0-9]+/ { print $1, $2, $3, $4, ($4/$3*100), $5, $6 }'

[root@tiny ~]# ./test.sh
API 20042017-01:00 341701 341701 100 100 480692
API 20042017-02:00 293058 293058 100 100 415459
API 20042017-03:00 272692 272692 100 100 388942
API 20042017-04:00 279117 279115 99.9993 100 399361
API 20042017-05:00 345947 345945 99.9994 100 495306
[root@tiny ~]# 
  • It works,, actually i am getting FATAL error if there is a zero value also "awk: (FILENAME=- FNR=2) fatal: division by zero attempted", hence i have used "'$3 ~ /^[1-9]+/ && $4 ~ /^[1-9]+/".. Thanks a lot. – RNL Jul 24 '17 at 2:05
  • 1
    That won't match anything with a zero in it at all. What do you want to happen when you find something invalid? – xrobau Jul 24 '17 at 2:33
  • 1
    you could use something like $3 * 1 == $3 && $3 != 0 { ... }. – cas Jul 24 '17 at 5:01

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.