【问题标题】:syntax error: invalid arithmetic operator (error token is "")语法错误:算术运算符无效(错误标记为“”)
【发布时间】:2014-03-18 13:44:56
【问题描述】:

我正在尝试编写一个函数,逐行检查文本文件,按某些条件检查每个字段,然后将其全部汇总。我使用完全相同的方式对每一个 cretirias 求和,但是对于第四个(在代码中是时间)我在标题中得到错误。我尝试删除总结时间的行,我的代码工作得很好,我不知道这行有什么问题,而且我对 Bash 还是很陌生。我们将不胜感激每一点帮助!

代码如下:

#!/bin/bash
valid=1
sumPrice=0
sumCalories=0
veganCheck=0
sumTime=0
function checkValidrecipe
{
    while read -a line; do
        if (( ${line[1]} > 100 )); then
            let valid=0
        fi
        if (( ${line[2]} > 300 )); then
            let valid=0
        fi
        if (( ${line[3]} != 1 && ${line[3]} != 0 )); then
            let valid=0
        fi
        if (( ${line[3]} == 1)); then
            veganCheck=1
        fi
        let sumPrice+=${line[1]}
        let sumCalories+=${line[2]}
        let sumTime+=${line[4]}
    done < "$1"
}
checkValidrecipe "$1"
if (($valid == 0)); then
    echo Invalid
else
    echo Total: $sumPrice $sumCalories $veganCheck $sumTime
fi

我可以假设每个输入文件都采用以下格式:

name price calories vegancheck time

我正在尝试使用此输入文件运行脚本:

t1 50 30 0 10
t2 10 35 0 10
t3 75 60 1 60
t4 35 31 0 100
t5 100 30 0 100

(包括空行)

这是输出:

")syntax error: invalid arithmetic operator (error token is "
")syntax error: invalid arithmetic operator (error token is "
")syntax error: invalid arithmetic operator (error token is "
")syntax error: invalid arithmetic operator (error token is "
")syntax error: invalid arithmetic operator (error token is "
Total: 270 186 1 0

非常感谢您的帮助!

【问题讨论】:

    标签: bash


    【解决方案1】:

    您的输入文件包含 CR+LF 行结尾。因此,变量${line[4]} 不是像10 这样的数字,而是导致错误的10\r

    使用dos2unix等工具从输入文件中删除回车。

    或者,您可以通过修改来更改脚本以处理它

    done < "$1"
    

    done < <(tr -d '\r' < "$1")
    

    【讨论】:

    • 哇!感谢您的快速回复!我在我的脚本上使用了 dos2unix,但没有在输入文件上使用,所以现在在我在输入文件上使用它之后,它工作得很好。非常感谢你!祝你有美好的一天:)
    • dos2unix 工具非常棒!立即摆脱了错误。
    猜你喜欢
    • 2014-10-05
    • 1970-01-01
    • 1970-01-01
    • 2017-07-15
    • 2018-12-13
    • 2019-04-16
    • 1970-01-01
    • 1970-01-01
    • 2012-02-20
    相关资源
    最近更新 更多