我想在bson上迭代这个json字符串(使用jq
生成):
{
"hostname": "Arthhur",
"long": 10.234656,
"lat": 54.3454345
}
{
"hostname": "Zaphod",
"long": 10.12344324,
"lat": 54.35672134
}
...
使用以下命令从该位置生成zipcodes:
plz=`wget -qO - "http://maps.googleapis.com/maps/api/geocode/json?latlng=$lat,$lng&sensor=true"|grep '"[0-9][0-9][0-9][0-9][0-9]"'|head -n1`
plz=${plz##*\ :\ \"}
plz=${plz%%\"*}
如何将字符串传递给bash循环,所以我可以为每个主机名调用wget命令,在循环内部有两个变量用于long和lat?
答案 0 :(得分:1)
仍然有点困惑为什么你将原始json
解析为仍然需要解析的东西,但是这样的东西通常应该适用于特定的字符串
#!/bin/bash
unset lat long hostname
while IFS= read -r line; do
[[ $line =~ '"hostname": "'([^\"]+) ]] && hostname=${BASH_REMATCH[1]}
[[ $line =~ '"long": '([^,[:space:]]+) ]] && long=${BASH_REMATCH[1]}
[[ $line =~ '"lat": '([^,[:space:]]+) ]] && lat=${BASH_REMATCH[1]}
if [[ -n $hostname && -n $long && -n $lat ]]; then
echo "Hostname=[$hostname], Lat=[$lat], Long=[$long]" #or whatever else with them
unset lat long hostname
fi
done < file
即
> cat file
{
"hostname": "Arthhur",
"long": 10.234656,
"lat": 54.3454345
}
{
"hostname": "Zaphod",
"long": 10.12344324,
"lat": 54.35672134
}
> ./abovescript
Hostname=[Arthhur], Lat=[54.3454345], Long=[10.234656]
Hostname=[Zaphod], Lat=[54.35672134], Long=[10.12344324]