jpints14
jpints14

Reputation: 1371

How to format string with numbers and decimals?

My text.csv file looks like this. I want to truncate the floating point numbers using the awk command.

ZAR Spot Up 8%,10011569,1.1234873687000001
ZAR Spot Up 8%,10011584,0.8789456464999999
ZAR Spot Up 8%,10011587,0.4543572142000001

I am doing this:

awk '{ FS = "," ; printf(sprintf("%s,%d,%.10f\n",$1,$2,$3))}' text.csv

However, the "%s" is formatting the first column in a weird way

ZAR,0,0.0000000000
ZAR Spot Up 8%,10011584,0.8789456465
8ZAR Spot Up 8%,10011587,0.4543572142

Where as I would like something like

ZAR Spot Up 8%,10011569,1.1234873687
ZAR Spot Up 8%,10011584,0.8789456465
ZAR Spot Up 8%,10011587,0.4543572142

I believe it has something to do with the '8' or the '%' sign. Any idea what the correct command is?

Upvotes: 0

Views: 737

Answers (2)

Ed Morton
Ed Morton

Reputation: 203254

You are using data in the printf format, data format argument location and that data contains a formatting character (%). Just don't do that, use printf format, data as per the synopsis.

Specifically in your case you are doing (note printf is getting one argument):

printf sprintf("%s,%d,%.10f\n",$1,$2,$3)

so the output of sprintf which includes % characters is the first arg to printf and that's where the format arg goes. If you changed it to:

printf "%s", sprintf("%s,%d,%.10f\n",$1,$2,$3)

then you wouldn't have the problem but of course the sprintf is superfluous since you could just write:

printf "%s,%d,%.10f\n",$1,$2,$3

and in this case since you really only want to modify the 3rd field your whole script could just be:

awk 'BEGIN{FS=OFS=","} {$3=sprintf("%.10f",$3)} 1' text.csv

Upvotes: 1

tripleee
tripleee

Reputation: 189347

You need to set FS much earlier in your script; the first line of input has already been read and parsed by the time you assign it.

In addition, the double printf is obviously superfluous.

awk -F, '{ printf("%s,%d,%.10f\n",$1,$2,$3)}' text.csv

Upvotes: 1

Related Questions