0

我的代码的目的是

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

这是我的代码。它在 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 条件没有被检查,这将是以下输出的原因。

基准时间为 2.94
所有技术关闭 = 3.09
阈值为 0.15


基准时间是 3.07
所有技术关闭 = 2.96
阈值为 -.11

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

4

2 回答 2

2

你用的是什么外壳?我假设只是简单的旧“sh”或“bash”。

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

if($Threshhold<0) 那么

将其切换为:

如果 [ $Threshold -lt 0 ]; 然后

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

为了进一步扩展,我敲了测试脚本和数据(请注意我将“阈值”更改为“阈值”):

# 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
于 2013-01-02T05:07:09.950 回答
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
于 2013-01-02T05:27:21.923 回答