删除科学记数法 bash 脚本

ppn*_*air 5 bash shell-script arithmetic floating-point

当我将 MB 转换为 GB 时,我的输出低于输出。我想要正常格式的输出。当我使用时,bc我收到一个错误。文本文件包含近 100 行这样的行。

我想在正常输出中打印它,(不带符号):

1.14441e-07
4.95911e-07
3.05176e-07
1.90735e-07
3.05176e-07
Run Code Online (Sandbox Code Playgroud)

命令:

$ DIVISOR=104857600
$ sudo  du --max-depth=1 /home/xxx | tail -1 | \
      awk -v DIVISOR=104857600 '{print $1/DIVISOR}'
1.14441e-07
Run Code Online (Sandbox Code Playgroud)

Kyl*_*nes 5

awk 有一个 sprintf 函数,它使您可以访问 printf "f" 格式说明符。

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

产生

0.123456000
Run Code Online (Sandbox Code Playgroud)


slm*_*slm 5

要控制输出的格式,您可以printf直接从awkshell 或直接通过 shell 使用。

但是,您也可以使用 直接控制输出du。例如,您可以指定-h以人类可读的格式输出结果。

例子

$ 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
Run Code Online (Sandbox Code Playgroud)

使用 printf 格式化

但是正如您所注意到的那样,使用此方法会丢失分辨率。因此,如果您真的想保持更高的分辨率,则必须从du较低级别获取值,然后格式化输出以适合您想要的更高级别的单位。

例子

在 MB 中使用du.

$ du -m --apparent-size --max-depth=1 /home/saml/apps | tail -1
8916    /home/saml/apps
Run Code Online (Sandbox Code Playgroud)

使用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
Run Code Online (Sandbox Code Playgroud)

您可以通过将参数更改为 来控制所需的精度printf。这里有5个地方。

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

请注意,无论何时您决定切断精度,都需要小心地将其四舍五入。