2017-06-22 11 views
0

私はbashスクリプトの仕組みを学んでおり、辞書の配列から値を取得する方法を知る必要があります。私は、宣言のためにこれをやった:辞書の配列から値を取得するbash

echo ${person[name]} 
# Bob 

をしかし、私は、配列の値にアクセスしようとすると、それは動作しません:

declare -a persons 
declare -A person 
person[name]="Bob" 
person[id]=12 
persons[0]=$person 

私はそれを次のような場合は、正常に動作します。私はこれらのオプションを試しました:

echo ${persons[0]} 
# empty result 
echo ${persons[0][name]} 
# empty result 
echo persons[0]["name"] 
# persons[0][name] 
echo ${${persons[0]}[name]} #It could have worked if this work as a return 
# Error 

私はもう何をしようとします。どんな助けもありがとう!

ありがとうございます!

バッシュバージョン:4.3.48

+1

bashは2次元配列をサポートしていません。 'perl'、' php'、 'python'などを使用してください。 – anubhava

+0

@anubhava次に、カールして出力を変数に保存したい場合は、変数の値にアクセスできますか? –

+0

他の言語にはURLを内部的に取得するための独自のライブラリがあります。 'curl'のような外部プログラムを実行する必要はありません。 – chepner

答えて

1

多次元配列をbashでサポートされていないの概念、そう

${persons[0][name]} 

は動作しません。しかし、Bash 4.0からは、bashには連想配列があります。これは試したようですが、テストケースに合っています。たとえば、次のようにすることができます。

#!/bin/bash 
declare -A persons 
# now, populate the values in [id]=name format 
persons=([1]="Bob Marley" [2]="Taylor Swift" [3]="Kimbra Gotye") 
# To search for a particular name using an id pass thru the keys(here ids) of the array using the for-loop below 

# To search for name using IDS 

read -p "Enter ID to search for : " id 
re='^[0-9]+$' 
if ! [[ $id =~ $re ]] 
then 
echo "ID should be a number" 
exit 1 
fi 
for i in ${!persons[@]} # Note the ! in the beginning gives you the keys 
do 
if [ "$i" -eq "$id" ] 
then 
    echo "Name : ${persons[$i]}" 
fi 
done 
# To search for IDS using names 
read -p "Enter name to search for : " name 
for i in "${persons[@]}" # No ! here so we are iterating thru values 
do 
if [[ $i =~ $name ]] # Doing a regex match 
then 
    echo "Key : ${!persons[$i]}" # Here use the ! again to get the key corresponding to $i 
fi 
done 
+0

この場合、idをIndexとして保存できますか?私は名前だけを持っていれば私はIDを検索したいですか? –

+0

@AlbertoLópezPérezforループを逆にして、編集を待つことができます。 – sjsam

+0

これは私の場合にはうまくいきますが、IDの代わりに例えば...国の場合はこれが違うと思います。私が間違っていたら、私に訂正してください。 –

関連する問題