问题描述
我试图写一个函数检查一个文本文件,一行行,某些cretirias检查每个字段,然后总结这一切。我使用的是完全相同的方式来总结cretirias中的每一个,但是对于4一(在code这将是一次)我得到错误的称号。我试图消除,总结我的code工作就好了时间和路线,我不知道这有什么错行了,我pretty新猛砸。帮助每一位将AP preciated!
I am trying to write a function the checks a text file, line by line, checking each field by certain cretirias, and then sums it all up. I am using the exact same way to sum each one of cretirias, but for the 4th one (in the code it will be time) I get the error in the title. I tried removing the line that sums the time and my code worked just fine, I have no clue what's wrong with the line and I'm pretty new to Bash. Every bit of help will be appreciated!
这里的code:
#!/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
和我认为每一个输入文件将在以下格式:
And I can assume that every input file will be in the following format:
name price calories vegancheck time
我试图运行与此输入文件中的脚本:
I am trying to run the script with this input file:
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
非常感谢你的帮助!
Thank you very much for your help!
推荐答案
您输入文件包含CR + LF行结束符。因此,变量 $ {行[4]}
不是像 10
若干但 10 \\ r
这将导致错误。
Your input file contains CR+LF line endings. As such, the variable ${line[4]}
isn't a number like 10
but 10\r
which causes the error.
删除使用工具输入文件中的回车符,如 DOS2UNIX的
。
Remove carriage returns from the input file using a tool such as dos2unix
.
另外,你可以改变你的脚本,通过修改来处理它。
Alternatively, you could change your script to handle it by modifying
done < "$1"
到
done < <(tr -d '\r' < "$1")
这篇关于语法错误:无效的算术运算符(错误标记是&QUOT;&QUOT;)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!