Issue
What I need is to increase the value of a variable dynamically (within a loop) by another variable. Here is my code:
while read Plate City Town Village Area Population; do
echo "$Plate $City $Town $Village $Area $Population"
printf "\n$totalNumberOfTowns\n "
totalNumberOfTowns=$totalNumberOfTowns+$Town
totalNumberOfVillages=$totalNumberOfVillages+$Village
done < "cities.txt"
what I get when I run my code is a little bit not-correct.
I didn't understand why there is "Town" inside $totalNumberOfTowns variable. Another interesting part is it also does calculation(it sums third parameter which is number of town in that city. For ADANA it is 15 and for ADIYAMAN it is 9 and so on.).
Edit:
First line of cities.txt is:
Plate City Town Village Area Population
see screenshot:
Edit-2: # I have tried these different syntaxes:
let "totalNumberOfTowns+=$Town" #1 I tried these different syntaxes
totalNumberOfTowns=$((expr $totalNumberOfTowns + $Town)) #2
totalNumberOfTowns=$((totalNumberOfTowns + Town)) #3
Yet, each of them gave me some errors.
Here are sample cities.txt and sample code:
Plate City Town Village Area Population 1 ADANA 15 508 14030 2258718 2 ADIYAMAN 9 420 7614 632459 3 AFYONKARAHİSAR 18 395 14230 736912 4 AĞRI 8 566 11376 535435 5 AMASYA 7 352 5520 335494 6 ANKARA 25 711 25706 5663322 7 ANTALYA 19 545 20723 2548308 34 İSTANBUL 40 166 5196 15462452
code
#!/usr/bin/env bash
average=0
numberOfCities=80
declare -i totalNumberOfTowns=0 totalNumberOfVillages=0
arrayWithOut=""
while read Plate City Town Village Area Population; do
echo "$Plate $City $Town $Village $Area $Population"
printf "\n$totalNumberOfTowns\n "
totalNumberOfTowns+=$Town
totalNumberOfVillages+=$Village
done < "cities.txt"
Solution
You have to ignore first line.
#!/usr/bin/env bash
average=0
numberOfCities=80
declare -i totalNumberOfTowns=0 totalNumberOfVillages=0
arrayWithOut=""
{
read -r first_line
while read -r Plate City Town Village Area Population; do
echo "$Plate $City $Town $Village $Area $Population"
printf "\n$totalNumberOfTowns\n "
totalNumberOfTowns+=$Town
totalNumberOfVillages+=$Village
done
} < "cities.txt"
Answered By - KamilCuk Answer Checked By - Marilyn (WPSolving Volunteer)