我需要的是通過另一個變數動態地(在回圈內)增加一個變數的值。這是我的代碼:
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"
運行代碼時得到的結果有點不正確。

我不明白為什么 $totalNumberOfTowns 變數中有“Town”。另一個有趣的部分是它還進行計算(它將第三個引數相加,即該城市的城鎮數量。對于 ADANA,它是 15,對于 ADIYAMAN,它是 9,依此類推。)。
編輯:
city.txt 的第一行是:
板市鎮村區人口
看截圖:

Edit-2: # 我嘗試過這些不同的語法:
let "totalNumberOfTowns =$Town" #1 I tried these different syntaxes
totalNumberOfTowns=$((expr $totalNumberOfTowns $Town)) #2
totalNumberOfTowns=$((totalNumberOfTowns Town)) #3
然而,他們每個人都給了我一些錯誤。
以下是示例 city.txt 和示例代碼:
平板城市城鎮村莊地區人口1 Adana 15 508 14030 2258718 2 Adiyaman 9 420 7614 632459 3 afyonkarahiSar 18 395 14230 736912 4A?ri8 5666666666611376 11376 535435 535435 5 AMASYA 7 352 5520 333 333 33 3334 6 AN ANINALY 33 3334 6 AN AN ANANAKARAKARAKARARA 40 166 5196 15462452
代碼
#!/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"
uj5u.com熱心網友回復:
您必須忽略第一行。
#!/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"
uj5u.com熱心網友回復:
您還可以使用具有整數屬性的變數:
#!/usr/bin/env bash
declare -i totalNumberOfTowns=0 totalNumberOfVillages=0
while read Plate City Town Village Area Population; do
printf "%s %s %s %s %s %s\n" "$Plate" "$City" "$Town" "$Village" "$Area" "$Population"
totalNumberOfTowns =$Town
totalNumberOfVillages =$Village
done < "cities.txt"
printf "Total towns: %d\nTotal villages: %d\n" "$totalNumberOfTowns" "$totalNumberOfVillages"
uj5u.com熱心網友回復:
我什至知道三種在 bash 中計算的方法:
命令 expr(運算子: 、-、*、/、%、(、);和邏輯運算子:<、<=、==、!=、>=、>)
expr 2 * 3(運算子前的空格和''符號很重要)
或者
a=5;a=$(expr $a 1)
語法 (( <expression> )) - C 語言中已知的所有運算子
a=0;a=$((a 1))
命令讓
x=0;讓“x = 2”
uj5u.com熱心網友回復:
例如,只需將運算式放在雙括號中$((your_expression))
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"
uj5u.com熱心網友回復:
一個可行的(而且很可能更快)的awk替代方案。
awk '
NR==1{print}
NR>1{a =$3;b =$4;print}
END{
print "Total number of towns:",a
print "Total number of villages:",b
}' cities.txt
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/532823.html
標籤:linux重击整数
