UNIX shell脚本中的浮点算法

Dav*_*eer 10 unix math floating-point shell

如何在shell脚本中使用1.503923等浮点数进行算术运算?浮点数作为字符串从文件中提取.该文件的格式如下:

1.5493482,3.49384,33.284732,23.043852,2.2384...
3.384,3.282342,23.043852,2.23284,8.39283...
.
.
.
Run Code Online (Sandbox Code Playgroud)

这是一些我需要工作的简化示例代码.一切都很好,直到算术.我从文件中拉出一行,然后从该行中提取多个值.我认为这会减少搜索处理时间,因为这些文件非常庞大.

# set vars, loops etc.

while [ $line_no -gt 0 ]
do
    line_string=`sed -n $line_no'p' $file_path`  # Pull Line (str) from a file
    string1=${line_string:9:6}                   # Pull value from the Line
    string2=${line_string:16:6}
    string3=...
    .
    .
    .
    calc1= `expr $string2 - $string7` |bc -l     # I tried these and various
    calc2= ` "$string3" * "$string2" ` |bc -l    # other combinations
    calc3= `expr $string2 - $string1`
    calc4= "$string2 + $string8" |bc
    .
    .
    .
    generic_function_call                        # Use the variables in functions
    line_no=`expr $line_no - 1`                  # Counter--
done
Run Code Online (Sandbox Code Playgroud)

输出我一直得到:

expr: non-numeric argument
command not found
Run Code Online (Sandbox Code Playgroud)

Oli*_*lac 11

我相信你应该使用: bc

例如:

echo "scale = 10; 123.456789/345.345345" | bc
Run Code Online (Sandbox Code Playgroud)

(这是unix的方式:每个工具都专注于做他们应该做的事情,他们都在一起做伟大的事情.不要模仿另一个伟大的工具,让他们一起工作.)

输出:

.3574879198
Run Code Online (Sandbox Code Playgroud)

或者用比例1代替10:

echo "scale = 1; 123.456789/345.345345" | bc
Run Code Online (Sandbox Code Playgroud)

输出:

.3
Run Code Online (Sandbox Code Playgroud)

请注意,这不会执行舍入.


jgr*_*jgr 6

那这个呢?

calc=$(echo "$String2 + $String8"|bc)
Run Code Online (Sandbox Code Playgroud)

这将bc添加$ String2和$ String8的值,并将结果保存在变量中calc.


igr*_*eld 6

如果你没有"bc",你可以使用'awk':

calc=$(echo 2.3 4.6 | awk '{ printf "%f", $1 + $2 }')
Run Code Online (Sandbox Code Playgroud)