Zin
Zin

Reputation: 149

Csv file column calculation

In csv file I have below columns and I try to change the second column's value with

$ awk -v FS="\",\"" -v OFS="\",\"" '{$2=sprintf("%.2f",$2*2)}1' file.csv

But some columns contains string which must remain unchanged. I know

"^[0-9][0-9]*$" 

will check if it is number but how to combine it in my command?

file.csv

"sku","NO price","supplierName"
"sku","3.14","supplierName"
"sku","3.56","supplierName"
"sku","4.20","supplierName"

Upvotes: 1

Views: 39

Answers (1)

anubhava
anubhava

Reputation: 785246

You can use:

awk -v FS='","' -v OFS='","' '$2+0 == $2{$2=sprintf("%.2f",$2*2)}1' file.csv
"sku","NO price","supplierName"
"sku","6.28","supplierName"
"sku","7.12","supplierName"
"sku","8.40","supplierName"

$2+0 == $2 check makes sure that value in $2 is numeric.

Upvotes: 1

Related Questions