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=$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
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.
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:
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=$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