如何在Ubuntu中使用shell脚本从文件中提取十进制值?

时间:2013-01-02 04:59:39

标签: shell gcc

我的代码的目的是

  • 从两个单独的文件中读取两个值。 [工作得很好]
  • 将它们转换为十进制值。 [工作正常]
  • 找出他们的不同之处。 [工作正常]
  • 如果是负值,则使差异为正。 [不工作,它没有检查条件。]

这是我的代码。它在Ubuntu 11.04中编码。

...
while read line;
do
echo -e "$line";
AllOn=$line
done<Output.log

gcc -Wall -o0 Test.c -o output
time -f "%e" -o BaseFile.log ./output
while read line;
do
echo -e "$line";
AllOff=$line
done<BaseFile.log

#Threshold Value
Threshold=`echo "$AllOff - $AllOn" | bc`;
echo "Threshold is $Threshold"
if [ `echo "$Threshold < 0.00"|bc` ]; then
   Threshold=`echo "$Threshold * -1" | bc`;
fi
echo "\nThreshold is $Threshold" >> $Result

现在,无论价值如何,if clause都会被执行。我认为,我的if条件没有被检查,并且这将是以下输出的原因。

Base Time is 2.94
All Techniques Off = 3.09
Threshold is .15


Base Time is 3.07
All Techniques Off = 2.96
Threshold is -.11

更新:这个问题还没有完全回答,如果有人能建议我实现 找到差异的第四个目标 在价值观之间,对我来说真的很有帮助。谢谢。

2 个答案:

答案 0 :(得分:2)

你使用的是什么外壳?我假设只是简单的'sh'或'bash'。

如果是这样,请查看第33行:

  

if($ Threshhold&lt; 0)然后

将其切换为:

  

if [$ Threshhold -lt 0];然后

您可能还有其他问题,我没有密切查看代码以检查它们。

为了进一步扩展,我敲了测试脚本和数据(请注意我将'Threshhold'更改为'Threshold'):

# Example test.sh file
!/bin/bash

while read line;
do
echo "$line";
AllOn=$line
done < Output.log

while read line;
do
echo "$line";
AllOff=$line
done < BaseFile.log

#Threshhold Value
Threshold=`echo "$AllOn - $AllOff" | bc`;
echo "Threshold is $Threshold"
if [ `echo "$Threshold < 0"|bc` ]; then
  # snips off the '-' sign which is what you were trying to do it looks
  Threshold=${Threshold:1}
fi
echo $Threshold
Result=result.txt
echo "\nThreshold is $Threshold" >> $Result

然后是一些数据文件,首先是Output.log:

# Output.log
1.2

然后是BaseFile.log:

# BaseFile.log
1.3

以上输出示例:

./test.sh
1.2
1.3
Threshold is -.1
.1

答案 1 :(得分:1)

Bourne shell没有内置的算术功能。作业

Threshhold=$AllOn-$AllOff

简单地将两个字符串连接起来,并在它们之间加一个减号。

在Bash中,您可以使用

Threshhold=$(($AllOn-$AllOff))

但仍然不允许比较为零。为了便于携带,我只是将Awk用于整个任务。

#!/bin/sh
gcc -Wall -o0 Test.c -o output
time -f "%e" -o BaseFile.log ./output
awk 'NR==FNR { allon=$0; next }
    { alloff=$0 }
    END { sum=allon-alloff; 
        if (sum < 0) sum *= -1; 
        print "Threshold is", sum }' Output.log BaseFile.log >>$Result