UNIX shell 脚本中的浮点运算 [英] Floating-point arithmetic in UNIX shell script

查看:30
本文介绍了UNIX shell 脚本中的浮点运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to do arithmetic with floating point numbers such as 1.503923 in a shell script? The floating point numbers are pulled from a file as a string. The format of the file is as follows:

1.5493482,3.49384,33.284732,23.043852,2.2384...
3.384,3.282342,23.043852,2.23284,8.39283...
.
.
.

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

Here is some simplified sample code I need to get working. Everything works fine up to the arithmetic. I pull a line from the file, then pull multiple values from that line. I think this would cut down on search processing time as these files are huge.

# 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

我不断得到的输出:

expr: non-numeric argument
command not found

推荐答案

这个怎么样?

calc=$(echo "$String2 + $String8"|bc)

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

This will make bc to add the values of $String2 and $String8 and saves the result in the variable calc.

这篇关于UNIX shell 脚本中的浮点运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆