I've created a bash script to find dollar words. For those of you who don't know, a dollar word is a word whose values of their letters add up to 100 when A is given a value of 1, B is given a value of 2, C is 3, and all the way to Z is 26.
I am new to programming, so I've created a very crude script that'll do this kind of thing, but it's not working as fast as I would expect. Something in my code is slowing it down, but I don't know what. This is my code.
#!/bin/bash
#370101 total words in Words.txt
line=$(cat line.txt)
function wordcheck {
letter=({a..z})
i=0
while [ "$i" -le 25 ]
do
occurences["$i"]=$(echo $word | grep ${letter["$i"]} -o | wc -l)
((i++))
done
((line++))
}
until [ "$line" -ge "370102" ]
do
word=$(sed -n "$line"p Words.txt)
wordcheck
echo "$line" > line.txt
x=0
while [ "$x" -le '25' ]
do
y=$((x+1))
charsum["$x"]=$((${occurences[x]} * $y))
((x++))
done
wordsum=0
for n in ${charsum[@]}
do
(( wordsum += n ))
done
tput el
printf "Word #"
printf "$(($line - 1))"
if [ "$wordsum" = '100' ]
then
echo $word >> DollarWords.txt
printf "\n\n"
printf "$word\n"
printf '$$$DOLLAR WORD$$$\n\n'
else
printf " Not A Dollar Word $word\n"
tput cuu1
fi
done
I can only speculate that it has something to do with the while loops, or with how it is constantly writing the value of $line
to a file.
I've created a script before that adds numbers to generate the Fibonacci sequence, and it does it almost instantaneously.
So my question is, what are some ways to help my code run more efficiently? Apologies if this belongs on codereview.
Any help is highly appreciated.
Thanks
Edit:
Although I accepted Gordan Davisson's Answer, the other ones are just as good if you want to do this. I'd recommend reading everyone else's answer before giving this a try. Also, as numerous users have pointed out, bash is not a good language to be using for this. Again, Thanks to everyone for your suggestions.