替换现有文件中浮点数的精度 [英] Replacing precision of floating point numbers in existing file
问题描述
我有许多以下格式的大文件
I have a large number of big files in the following format
step 80
1.10045e+07 1.10125e+07 1.20345e+07 2.40225e+07 4.30245e+07
1.10045e+07 1.10125e+07 1.20345e+07 2.40225e+07 4.30245e+07
1.10045e+07 1.10125e+07 1.20345e+07 2.40225e+07 4.30245e+07
1.10045e+07 1.10125e+07 1.20345e+07 2.40225e+07 4.30245e+07
step 90
1.54045e+07 1.10125e+07 1.20345e+07 2.40225e+07 4.30245e+07
1.16545e+07 1.10125e+07 1.20345e+07 2.40225e+07 4.30245e+07
1.10045e+07 1.10125e+07 1.20345e+07 2.40225e+07 4.30245e+07
1.10045e+07 1.10125e+07 1.20345e+07 2.40225e+07 4.30245e+07
...
数字都是不同的(由于我的懒惰,这里有些数字相同).
The numbers are all distinct (some are the same here because of my laziness).
我想更改浮点数的精度.也就是说,我想将以前的文件替换为:
I want to to change the precision of the floating-point numbers. That is, I want to replace the previous file with:
step 80
1.10e+07 1.10e+07 1.20e+07 2.40e+07 4.30e+07
1.10e+07 1.10e+07 1.20e+07 2.40e+07 4.30e+07
1.10e+07 1.10e+07 1.20e+07 2.40e+07 4.30e+07
1.10e+07 1.10e+07 1.20e+07 2.40e+07 4.30e+07
step 90
1.54e+07 1.10e+07 1.20e+07 2.40e+07 4.30e+07
1.16e+07 1.10e+07 1.20e+07 2.40e+07 4.30e+07
1.10e+07 1.10e+07 1.20e+07 2.40e+07 4.30e+07
1.10e+07 1.10e+07 1.20e+07 2.40e+07 4.30e+07
...
如果所需的精度是小数点后2位.
if the desired precision is 2 digits after the decimal point.
如何以一种高效的方式做到这一点,并且内存使用率低(也就是说,我不必将整个文件加载到内存中).
How can I do this, in an efficient way, and low memory usage (that is, I don't to have to load the complete file to memory).
最好是使用bash脚本的解决方案.
Preferably a solution using a bash script.
推荐答案
You could use Perl to read the file line-by-line and reformat the numbers with sprintf()
:
perl -pe '!/^step/ && s/(\S+)/sprintf("%.2e", $1)/ge' file
这篇关于替换现有文件中浮点数的精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!