bash - 语法错误: invalid arithmetic operator (error token is ".")

标签 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 ".")

出了什么问题以及如何修复它?谢谢。

最佳答案

在第一次尝试中,您没有从 ${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

关于bash - 语法错误: invalid arithmetic operator (error token is "."),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25267951/

相关文章:

python - 使用参数从 bash 调用 Python 脚本

linux - 有没有办法在不重建其依赖项的情况下强制重建目标(make -B)?

bash - 在 bash 中将条件参数传递给curl

linux - 使用 bash shell 脚本在 2 个字符串之间提取字符串

json - 修改JSON jq中的键值数组

bash - 案例声明没有捕获空字符串

LINUX:如何输出 SQL 脚本中使用的表

bash - 重用 Makefile prerequesite 中的百分号作为子目录名称

Bash:变量的所有组合

linux - 使用 cat 和 tee 添加文件时的奇怪行为