文本文件中的算术运算

文本文件中的算术运算

我有一个如下的数据文件;

569158.650000 8.859e-02
579175.970000 8.659e-02
599177.990000 8.659e-02

我需要从第一列中提取第一行的值。然后我需要将第一列除以 3600。最后,我需要将结果粘贴为新数据文件中的第一列,如下所示;

0 8.859e-02
2.78 8.659e-02
8.33 8.659e-02

我如何使用代码进行上述计算?

答案1

以下是awk解决该问题的一种方法:

awk '{printf "%.2f %s\n", $1/3600, $2}'

对于每一行,这只是将第一个字段除以 3600 ( $1/3600),并将其打印为带有两个小数点的浮点数 ( %.2f),后跟空格,将第二个字段 ( $2) 打印为字符串 ( %s),最后是换行符。如果您想要四舍五入到小数点后六位,只需更改%.2f%.6f

示例运行

$ cat <data
569158.650000 8.859e-02
579175.970000 8.659e-02
599177.990000 8.659e-02
$ awk '{printf "%.2f %s\n", $1/3600, $2}' <data >new_data
$ cat <new_data 
158.10 8.859e-02
160.88 8.659e-02
166.44 8.659e-02
$ awk '{printf "%.6f %s\n", $1/3600, $2}' <data
158.099625 8.859e-02
160.882214 8.659e-02
166.438331 8.659e-02

答案2

#!/bin/bash                                                                     
div=3600 #Divisor
scale=2  #Scale for output. Number of digits after decimal point.
while read -r line #Read file into variable line, line by line.
do
    firstnum=$(echo $line | cut -d " " -f 1) #Pick the first number field
    secondnum=$(echo $line | cut -d " " -f 2) #Pick the second number field
    firstnum=$(echo "scale=${scale}; ${firstnum}/${div}" | bc -l) #Divide by $div with $scale places after decimal point.
    echo "${firstnum} ${secondnum}" >> output #Output first and second column, seperated by space,to file named output.
done < input #input is name of input file.

input该脚本从以您所述格式命名的文件读取,并输出到名为 的文件output

首先,它将行分成两个字段,然后将第一个字段除以 3600,并打印两个小数,然后将新数字和行中的第二个数字打印到名为 output 的文件中。

它不进行错误检查。如果遇到错误,YMMV。

相关内容