bash 语法错误:无效的算术运算符(错误标记为“.”)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25267951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 11:06:21  来源:igfitidea点击:

Syntax error: invalid arithmetic operator (error token is ".")

bashshellunixarithmetic-expressions

提问by kitsune

I have to search word occurrences in a plain text file using a script. The script that I wrote is:

我必须使用脚本搜索纯文本文件中出现的单词。我写的脚本是:

#!/bin/bash

if [ $# -ne 1 ]
then
        echo "inserire il file che si vuole analizzare: "
        read
        fileIn=$REPLY
else
        fileIn=
fi

echo "analisi di $fileIn"

for parola in $( cat $fileIn )
do
        freq=${vet[$parola]}
        vet[$parola]=$(( freq+1 ))
done

for parola in ${!vet[*]}
do
        echo $parola ${vet[$parola]}
done

unset array

But when I run it I get this error:

但是当我运行它时,我收到此错误:

./script02.sh: line 16: qua.: syntax error: invalid arithmetic operator (error token is ".")

What's wrong and how do I fix it? Thanks.

出了什么问题,我该如何解决?谢谢。

采纳答案by konsolebox

In the first attempt, you don't get a value from ${vet[$parola]}. This causes the syntax error for the arithmethic operation Use a default value instead:

在第一次尝试中,您没有从${vet[$parola]}. 这会导致算术运算的语法错误 使用默认值代替:

for parola in $(cat "$fileIn")
do
    freq=${vet[$parola]}
    [[ -z $freq ]] && freq=0
    vet[$parola]=$(( freq + 1 ))
done

You might also need to declare your array as associative if you want to store non-integer keys:

如果要存储非整数键,您可能还需要将数组声明为关联数组:

declare -A vet

for ...

Suggestion:

建议:

#!/bin/bash

if [[ $# -ne 1 ]]; then
    read -p "inserire il file che si vuole analizzare: " fileIn
else
    fileIn=
fi

echo "analisi di $fileIn"

declare -A vet  ## If you intend to use associative arrays. Would still work in any way.

for parola in $(<"$fileIn"); do
    freq=${vet[$parola]}
    if [[ -n $freq ]]; then
        vet[$parola]=$(( freq + 1 ))
    else
        vet[$parola]=1
    fi
done

for parola in "${!vet[@]}"; do
    echo "$parola ${vet[$parola]}"
done

unset vet  ## Optional