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

问题描述

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

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



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

 #设置变量,循环等

while [$ line_no -gt 0]
do
line_string =`sed -n $ line_no'p'$ file_path`#从文件中拉行(str)
string1 = $ {line_string:9:6}#从行
拉取值string2 = $ {line_string:16:6}
string3 = ...



calc1 =`expr $ string2 - $ string7` | bc -l#我试过这些和各种
calc2 =`$ string3*$ string2`| bc -l#其他组合
calc3 =`expr $ string2 - $ string1`
calc4 =$ string2 + $ string8| bc



generic_function_call#在函数
中使用变量line_no =`expr $ line_no - 1`#counter -
done

输出我一直得到:
$ b pre class =lang-none prettyprint-override> expr:非数字参数
命令未找到


解决方案

那么这个怎么样呢?
$ b $ $ $ $ $ $ $ $ $ $ $ $ $ $ $($ $ $ $ $ $ $ $ $ $ $ $ $ $ code


$ b $ bc 可以添加$ String2和$ String8的值,将结果保存在变量 calc


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

Output I keep getting:

expr: non-numeric argument
command not found
解决方案

What about this?

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

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

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

08-12 13:47