0

I have a csv file like this:

Row 1,1,4.50,
Row 2,8,0.30,
Row 3,14,0.30,
Row 4,2,2.50,
Row 5,20,0.30,

I want to multiply the second coulmn with the third and add the result as a fourth.

I got this simple awk command:

awk -F',' '{print $1 "," $2 "," $3 "," $2 * $3}' file

and I get:

Row 1,1,4.50,4.5
Row 2,8,0.30,2.4
Row 3,14,0.30,4.2
Row 4,2,2.50,5
Row 5,20,0.30,6

is there a way to format the output in the last coulmn like [N.NN]?

so I would get an output like this:

Row 1,1,4.50,4.50
Row 2,8,0.30,2.40
Row 3,14,0.30,4.20
Row 4,2,2.50,5.00
Row 5,20,0.30,6.00
4

You can use printf or sprintf for formatted output ex.

$ awk -F, '{printf "%s%.2f\n", $0, $2*$3}' file
Row 1,1,4.50,4.50
Row 2,8,0.30,2.40
Row 3,14,0.30,4.20
Row 4,2,2.50,5.00
Row 5,20,0.30,6.00

or

$ awk -F, '{print $0 sprintf("%.2f", $2*$3)}' file
Row 1,1,4.50,4.50
Row 2,8,0.30,2.40
Row 3,14,0.30,4.20
Row 4,2,2.50,5.00
Row 5,20,0.30,6.00
  • does $0 stand for all the columns from input file? – nath Jul 31 at 13:53
  • 1
    @nath essentially yes - it stands for the whole record, before it has undergone field splitting – steeldriver Jul 31 at 13:56

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.