Bash:迭代地图的正确方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2615371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 21:56:35  来源:igfitidea点击:

Bash: Correct way to Iterate over Map

bashmaphashtableiteration

提问by Lars Tackmann

In Bash I can create a map(hashtable) with this common construction

在 Bash 中,我可以使用这种常见构造创建地图(哈希表)

hput() {
  eval """"=''
}

hget() {
  eval echo '${'""'#hash}'
}

and then use it like this:

然后像这样使用它:

hput capitals France Paris
hput capitals Spain Madrid
echo "$(hget capitals France)"

But how do I best iterate over the entries in the map ?. For instance, in Java I would do:

但是我如何最好地迭代地图中的条目?例如,在 Java 中我会这样做:

for (Map.Entry<String, String> entry : capitals.entrySet()) {
  System.out.println("Country " + entry.getKey() + " capital " + entry.getValue());
}

is there a common way of accomplishing something similar in Bash ?.

在 Bash 中是否有一种通用的方法来完成类似的事情?

回答by ghostdog74

if you have bash 4.0 , you can use associative arrays. else you can make use of awks associative arrays

如果您有 bash 4.0,则可以使用关联数组。否则你可以使用 awks 关联数组

回答by Paused until further notice.

Here's one way to do it:

这是一种方法:

for h in ${!capitols*}; do indirect=$capitols$h; echo ${!indirect}; done

Here's another:

这是另一个:

for h in ${!capitols*}; do key=${h#capitols*}; hget capitols $key; done

And another:

还有一个:

hiter() { 
    for h in $(eval echo '${!''*}')
    do
        key=${h#*}
        echo -n "$key "
        hget  $key
    done
}
hiter capitols
France Paris
Spain Madrid

By the way, "capitol" is a building. A city is referred to as a "capital".

顺便说一下,“国会大厦”是一座建筑物。一个城市被称为“首都”。

回答by ZyX

hkeys() {
    set | grep -o "^[[:alnum:]]*=" | sed -re "s/^(.*)=/\1/g"
}
for key in $(hkeys capitols) ; do
    echo $key
done

And your hget function is wrong. Try this:

你的 hget 函数是错误的。尝试这个:

hput capitols Smth hash
hget capitols Smth

Second command should return the string hash, but it returned nothing. Remove ?#hash? string from your function.

第二个命令应该返回字符串哈希,但它什么都不返回。删除 ?#hash? 函数中的字符串。

Also, echo "$(hget capitols France)"is ambigious. You can use hget capitols Franceinstead.

还有,echo "$(hget capitols France)"暧昧。你可以hget capitols France改用。