Remove scientific notation bash script

11,087

Solution 1

awk has a sprintf function, which gives you access to the printf "f" format specifier.

echo  .123456 | awk '{ print sprintf("%.9f", $1); }'

produces

0.123456000

Solution 2

To control the formatting of the output you can use printf either directly from awk or directly via the shell.

However you can also control the output directly using du. For example you can specify -h to output the results in human readable formats.

Examples

$ du -h --max-depth=1 /home/saml/apps | tail -1
9.0G    /home/saml/apps

$ du -h --max-depth=1 /home/saml/apps/gCAD3D  | tail -1
1.1M    /home/saml/apps/gCAD3D

Formatting using printf

But as you've noticed you lose resolution with this method. So if you truly want to keep a higher degree of resolution, you're forced to take the values from du at a lower level, and then format the output to fit which ever higher level units you want.

Example

In MB's using du.

$ du -m --apparent-size --max-depth=1 /home/saml/apps | tail -1
8916    /home/saml/apps

Using awk + printf.

$ DIVISOR=10487600
$ du --apparent-size --max-depth=1 /home/saml/apps | \
      tail -1 | awk -v D=$DIVISOR '{printf "%.9f\n", $1/D}'
0.870499638

You can control the amount of precision you want by changing the argument to printf. Here's 5 places.

$ DIVISOR=10487600
$ du --apparent-size --max-depth=1 /home/saml/apps | \
      tail -1 | awk -v D=$DIVISOR '{printf "%.5f\n", $1/D}'
0.87050

Notice that it takes care to round it correctly where ever you decide to cut off the precision.

Share:
11,087

Related videos on Youtube

Sonu
Author by

Sonu

Updated on September 18, 2022

Comments

  • Sonu
    Sonu almost 2 years

    When I convert MB to GB I'm getting below output. I want this output in normal format. When I use bc I'm getting an error. The text file contains nearly 100 such lines like this.

    I want to print this in normal output, (without notation):

    1.14441e-07
    4.95911e-07
    3.05176e-07
    1.90735e-07
    3.05176e-07
    

    Commands:

    $ DIVISOR=104857600
    $ sudo  du --max-depth=1 /home/xxx | tail -1 | \
          awk -v DIVISOR=104857600 '{print $1/DIVISOR}'
    1.14441e-07
    
  • Drew Stephens
    Drew Stephens almost 10 years
    Sweet, this worked for me with RRDTool, which really likes to give scientific notation (e.g. 1404784800: 7.8472672909e+01) output.