【问题标题】:Shell - Syntax error in expression (error token is "16")Shell - 表达式中的语法错误(错误标记为“16”)
【发布时间】:2018-10-12 09:19:32
【问题描述】:

我正在为我的大学做一个项目,这是我第一次使用 Bash 进行编码。

我正在尝试浏览一个 .txt 文档,阅读每一行,并获取我需要的信息来进行总结。

.txt 文件如下所示:

83210:Henrique Gaspar:EIB2:911235444:metas@gmail.com:carro:BMW:82-RX-14:5:25:26 88110:Vasco Rapido:IB2:962222222:vrapid@gmail.com:mota:BMW:33-MT-99:3:5:16 88020:Maria Aguiar:EIB2:911555444:mguiar@gmail.com:carro:mercedes:88-TX-11:2:20:12

对于我正在做的事情,我需要将每个用户的最后一个数字的总和计算为 26+16+12。

现在,这是我的代码:

#!/bin/bash
echo -n "Nº de condutores: "
echo $(cat condutores.txt | wc -l)
echo -n "Nº de passageiros: "
echo $(cat passageiros.txt | wc -l)
echo -n "Saldo total dos condutores: "
x=0
linhas=$(cat condutores.txt | wc -l)
i=0
while [[ $i -le $linhas ]]; do
    sum=$(cat condutores.txt | head -$i | tail -$(( $linhas + 1 - $i )) | cut -d':' -f11)
    x=$((x+sum))
    i=$((i+1))
done
echo "$x"

我在这里写了完整的,所以没有遗漏任何东西。

这里的问题重要的是从第 7 行到第 15 行。 我不知道这是否是我遍历 condutores.txt 文件的每一行或任何其他内容的方式。但是我收到了这个错误:

Saldo total dos condutores: ./stats.sh: line 12: 26
16: syntax error in expression (error token is "16")
26

所以由于某种原因,它只读取 .txt 文档的第一行和第二行,但无法求和,有人可以帮我吗? 提前致谢。

【问题讨论】:

  • 您的$sum 包含多行,因此不能解释为数字。
  • 感谢您的回答,知道如何解决这个问题吗?

标签: bash shell syntax sum


【解决方案1】:

您的 $sum 包含多行,因此不能解释为数字。而且您的文本处理循环是一场噩梦,有一个更清洁的解决方案。看:

x=0
while IFS=: read -r a b c d e f g h i j k; do
    x=$((x+k))
done < condutores.txt
echo "$x"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多