我必须使用脚本搜索纯文本文件中出现的单词。我写的脚本是:
#!/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/