Linux 使用变量作为 bash 关联数组中的键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9761973/
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
Using variable as a key in an bash associative array
提问by Asgeir
I'm trying to read the English dictionary in Linux into an associative array, using the words as keys and and predefined string as a value. This way I can look up words by key to see if they exist. Also I need all to words to be lowercase. It's fairly simple but the bash syntax is getting in my way. When I run the code below, I get a 'bad array subscript' error. Any thoughts as to why that might be ?
我试图将 Linux 中的英语词典读入一个关联数组,使用单词作为键,使用预定义的字符串作为值。这样我就可以按键查找单词,看看它们是否存在。另外我需要所有单词都是小写的。它相当简单,但 bash 语法妨碍了我。当我运行下面的代码时,出现“错误数组下标”错误。关于为什么会这样的任何想法?
function createArrayFromEnglishDictionary(){
IFS=$'\n'
while read -d $'\n' line; do
#Read string into variable and put into lowercase.
index=`echo ${line,,}`
englishDictionaryArray[$index]="exists"
done < /usr/share/dict/words
IFS=$' \t\n'
}
回答by j?rgensen
$index
is empty at some point. You also have a rather totally pointless use of echoassuming you wanted the line verbatim and not whitespace compressed. Just use index="${line,,}"
.
$index
在某个时候是空的。假设您想要逐字逐行而不是压缩空格,您还可以完全毫无意义地使用 echo。只需使用index="${line,,}"
.
回答by glenn Hymanman
To use associative arrays in bash, you need bash version 4, and you need to declare the array as an associative array with declare -A englishDictionaryArray
要在 bash 中使用关联数组,您需要 bash 版本 4,并且需要将数组声明为关联数组 declare -A englishDictionaryArray
回答by philcolbourn
Combining your work and other answers, try this:
结合你的工作和其他答案,试试这个:
I'm using GNU bash, version 4.2.37(1)-release (x86_64-pc-linux-gnu)
我正在使用 GNU bash,版本 4.2.37(1)-release (x86_64-pc-linux-gnu)
#!/bin/bash
declare -A DICT
function createDict(){
while read LINE; do
INDEX=${LINE,,}
DICT[$INDEX]="exists"
done < /usr/share/dict/words
}
createDict
echo ${DICT[hello]}
echo ${DICT[acdfg]}
echo ${DICT["a's"]}
回答by Jobin
I think following example will help..
我认为下面的例子会有所帮助..
$ declare -A colour
$ colour[elephant]="black"
$ echo ${colour[elephant]}
black
$ index=elephant
$ echo ${colour["$index"]}
black