5

i have such a file

1.5000000000E-01 7.5714285714E+00 4.0000000000E-01
2.5000000000E-01 7.5714285714E+00 4.0000000000E-01

and i have to convert it to something like

0.15 7.57 0.40

i mean i want the numbers to be with only 2 decimals and not to be exponential. I want to use bash!

ayasha
  • 1,221
  • 5
  • 27
  • 46

3 Answers3

6

Using printf with awk:

$ awk '{printf "%.2f %.2f %.2f\n",$1,$2,$3}' file
0.15 7.57 0.40
0.25 7.57 0.40

Given more fields you would want to loop like:

$ awk '{for(i=1;i<=NF;i++)printf "%.2f ",$i;print "\n"}' file
0.15 7.57 0.40
0.25 7.57 0.40
Chris Seymour
  • 83,387
  • 30
  • 160
  • 202
4

This can work:

printf "%1.2f" $number

Test:

$ for i in 1.5000000000E-01 7.5714285714E+00 4.0000000000E-01 2.5000000000E-01 7.5714285714E+00 4.0000000000E-01;
do
   printf "%1.2f\n" $i
done
0.15
7.57
0.40
0.25
7.57
0.40

In your case,

cat file | xargs printf "%1.2f\n"

Test:

$ cat file | xargs printf "%1.2f\n"
0.15
7.57
0.40
0.25
7.57
0.40
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • This doesn't demonstrate how to read the input from the file and the original format of the file is lost. – Chris Seymour May 22 '13 at 08:41
  • We are not concatenating any files here so throw away the UUoC `xargs printf "%1.2f\n" < file` but this still destroys the file format. The best I came up with using `xargs` and `printf` is `xargs printf "%1.2f " < ~/file | xargs -n3 ` but it's not great :/ – Chris Seymour May 22 '13 at 09:21
  • why use echo/xargs in this case and not `printf "%1.2f\n" $i` ? – suspectus May 22 '13 at 10:16
2
$ cat numbers.txt
1.5000000000E-01 7.5714285714E+00 4.0000000000E-01
2.5000000000E-01 7.5714285714E+00 4.0000000000E-01

$ while read F1 F2 F3;do printf "%.2f %.2f %.2f\n" $F1 $F2 $F3;done < numbers.txt
0.15 7.57 0.40
0.25 7.57 0.40
Chris Seymour
  • 83,387
  • 30
  • 160
  • 202
Michał Šrajer
  • 30,364
  • 7
  • 62
  • 85