我正在尝试编写一个函数,检查文本文件,逐行检查,通过某些cretirias检查每个字段,然后将其全部加起来.我使用完全相同的方式来对每个cretirias求和,但是对于第4个(在代码中它将是时间)我在标题中得到错误.我尝试删除总计时间的行,我的代码工作得很好,我不知道该行有什么问题,我对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
Run Code Online (Sandbox Code Playgroud)
我可以假设每个输入文件都采用以下格式:
name price calories vegancheck time
Run Code Online (Sandbox Code Playgroud)
我试图用这个输入文件运行脚本:
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
Run Code Online (Sandbox Code Playgroud)
(包括空行)
这是输出:
")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
Run Code Online (Sandbox Code Playgroud)
非常感谢您的帮助!
dev*_*ull 20
您的输入文件包含CR + LF行结尾.因此,变量${line[4]}不是类似10但10\r会导致错误的数字.
使用诸如的工具从输入文件中删除回车符dos2unix.
或者,您可以通过修改来更改脚本以处理它
done < "$1"
Run Code Online (Sandbox Code Playgroud)
至
done < <(tr -d '\r' < "$1")
Run Code Online (Sandbox Code Playgroud)