krouch
krouch

Reputation: 105

How to use awk to edit multiple columns of csv-file

I would like to use awk to edit a .csv-file with different type of values, for example round all values of several distinct columns to the second decimal place. The other rows may contain float-values as well, but those shall be handled in a different way.

Assuming one row looks like the one below and I would like to edit the 7th, 8th, and 9th column (in fact they are much longer, but all relevant type of values are in this example, so it's just a matter of scale):

L ,P_005 ,250.092 ,20.0 ,-0.80 ,0.803443 ,0.23342 ,0.83728329 ,0.0 ,0.0 

The output should be

L ,P_005 , 250.092, 20.0, -0.80, 0.80, 0.23, 0.84, 0.0, E2=0.0 

Up to now I've always round the value of one column "x" using:

#/bin/sh
OLDIFS=$IFS
IFS = ","
file=$1
...
awk '{printf "%.2f",$x}' $1
...   
IFS=$OLDIFS

So how do I adapt this concept in a way, where I can

without writing down each column with a specific option?

Upvotes: 1

Views: 675

Answers (1)

James Brown
James Brown

Reputation: 37394

If I got your guestion right:

awk -F\; -v OFS=\; '
function foo(str) {
  if(match(str, /[0-9]+\.[0-9]+/, arr)) {
    gsub(/[0-9]+\.[0-9]+/, sprintf("%.2f",arr[0]), str)
  } 
  return str
} 
{
  for(i=1; i<=NF; i++) 
    printf "%s%s", foo($i),(i<NF?OFS:ORS)
}' test.in

It produced:

L;P_005;X 250; Y 20; Z 0; A 0.80; B 0.23; C 0.84; E1=0.00; E2=0.00 ,

.

Upvotes: 2

Related Questions