[英]awk array - ghost entries after comparison
我有一個包含兩個數組的簡單代碼段,以及一個if比較
// {
# Create an array
animals["goat"] = "4 legs"
animals["chicken"] = "2 legs"
animals["elefant"] = "4 legs"
for (animal in animals) {
print "Animal: " animal " has: " animals[animal]
}
zoo["lion"] = "4 legs"
zoo["leguana"] = "4 legs"
for (animal in zoo) {
if (animals[animal] != "2 legs") {
# do something
}
}
for (animal in animals) {
print "Again. Animal: " animal " has: " animals[animal]
}
}
輸入文件無關緊要。
因此問題出在帶有if語句的for循環中。 我希望它可以簡單地比較數組“ animals”中的不同值是否不等於“ 2條腿”,但這是怎么回事:
Animal: chicken has: 2 legs
Animal: goat has: 4 legs
Animal: elefant has: 4 legs
Again. Animal: chicken has: 2 legs
Again. Animal: goat has: 4 legs
Again. Animal: elefant has: 4 legs
Again. Animal: lion has:
Again. Animal: leguana has:
請注意,數組“動物”突然有了兩個新鍵,即獅身像,但沒有價值。 為什么會這樣呢? =! 不應分配值,而應僅查看鍵是否存在值,該鍵可能在數組中不存在。 是否可以通過在數組中創建鍵來檢查數組中可能不存在的鍵是否具有特定值?
您必須保護動物說明書中的動物[動物]
for (animal in zoo) {
if (animal in animals && animals[animal] != "2 legs") {
print "Then Animal:" animal
}
else {
print "Else Animal:" animal
}
}
最終我在這里找到了答案: https : //www.gnu.org/software/gawk/manual/html_node/Reference-to-Elements.html
要確定某個元素在數組中是否存在某個索引,請使用以下表達式:
數組中的indx
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.