0

I have a file with 174 fields. The first 4 fields are given below

1|2.3|2.3|34
1|0|0|34
1|0.0|0.0|34
1|11|11|34
1|.3|.3|34
1|-0.00|-0.00|34
1|1.67|1.67|34

I need to convert it into this:

1|2.30|2.30|34
1|0.00|0.00|34
1|0.00|0.00|34
1|11.00|11.00|34
1|0.30|0.30|34
1|0.00|0.00|34
1|1.67|1.67|34

I used the following but the last value came as 1|1.70|1.70|34.

awk 'BEGIN {OFS=FS="|"} {$2=$2+0.00;$3=$3+0.00; print $0 }' file1 > temp1
awk 'BEGIN {OFS=FS="|"} {$2=sprintf("%.2f",$2);$3=sprintf("%.2f",$3);print $0}' temp1 > temp2
4

With the numfmt utility from GNU Coreutils:

numfmt --delimiter='|' --field=2-3 --format='%.2f' < file
1|2.30|2.30|34
1|0.00|0.00|34
1|0.00|0.00|34
1|11.00|11.00|34
1|0.31|0.31|34
1|0.00|0.00|34
1|1.67|1.67|34

Adjust the field range --field=2-3 according to your requirements

  • 1
    Oooh. That's a useful tool. – roaima Apr 24 '18 at 19:21
  • @roaima I discovered it on here iirc - it can do all kinds of unit conversions as well, but I haven't delved into that – steeldriver Apr 25 '18 at 0:08
0

Your second awk construct is almost perfect. Try this

awk -F'|' 'BEGIN {OFS = FS} {$2 = sprintf("%0.2f", $2+0); $3 = sprintf("%0.2f", $3+0); print $0}'
1|2.30|2.30|34
1|0.00|0.00|34
1|0.00|0.00|34
1|11.00|11.00|34
1|0.30|0.30|34
1|0.00|0.00|34
1|1.67|1.67|34
  • I have 174 fields. For sample I have give 3 fields – Sivabalan Divya Apr 24 '18 at 18:38

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.