语法错误:无效的算术运算符(错误标记为"。")

时间:2014-08-12 15:12:10

标签: bash shell unix arithmetic-expressions

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

#!/bin/bash

if [ $# -ne 1 ]
then
        echo "inserire il file che si vuole analizzare: "
        read
        fileIn=$REPLY
else
        fileIn=$1
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

但是当我运行它时,我收到了这个错误:

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

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

1 个答案:

答案 0 :(得分:2)

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

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

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

declare -A vet

for ...

建议:

#!/bin/bash

if [[ $# -ne 1 ]]; then
    read -p "inserire il file che si vuole analizzare: " fileIn
else
    fileIn=$1
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