[英]parse JSON out from curl response using Sed or awk and assign to variable for later use
I am writing a bash script to be run on a linux appliance so I do not have access to install jq, I need to be able to use native Linux tools我正在编写要在 linux 设备上运行的 bash 脚本,因此我无权安装 jq,我需要能够使用本机 Linux 工具
curl --location --request POST "https://api-mp.meraki.com/api/v1/networks/12345/switch/stacks/12345/routing/interfaces" \
--header "X-Cisco-Meraki-API-Key: 123key" \
--header "Content-Type: application/json" \
--data '{
"name": "L3 int",
"subnet": "192.168.249.0/24",
"interfaceIp": "192.168.249.2",
"multicastRouting": "disabled",
"vlanId": 140,
"ospfSettings": {
"area": "0",
"cost": 1,
"isPassiveEnabled": true
}
}' | sed -n 's|.*"interfaceID":"\([^"]*\)".*|\1|p' > $newVar
the response from the server returns this:来自服务器的响应返回:
{
"interfaceId": "12345",
"name": "PA L3 DR Int",
"subnet": "192.168.249.0/24",
"interfaceIp": "192.168.249.2",
"multicastRouting": "disabled",
"vlanId": 140,
"ospfSettings": {
"area": "0",
"cost": 1,
"isPassiveEnabled": true
}
}
I then need to be able to access the interfaceID new variable in a query string paramter然后我需要能够访问查询字符串参数中的 interfaceID 新变量
You just got the case wrong ( ID
vs Id
in interfaceId
) and forgot about the space after :
, but you were close:您只是弄错了案例( ID
与interfaceId
中的Id
)并忘记了:
之后的空格,但您很接近:
$ sed -n 's|.*"interfaceId": *"\([^"]*\)".*|\1|p' file
12345
Using cat file
in place of your curl
command to show how to save that to a variable in case you don't know:使用cat file
代替您的curl
命令来展示如何将其保存到变量中,以防您不知道:
$ var=$(cat file | sed -n 's|.*"interfaceId": *"\([^"]*\)".*|\1|p')
$ echo "$var"
12345
Could you please try following.请您尝试以下操作。 Tested successfully in link https://ideone.com/EsdCQp在链接https://ideone.com/EsdCQp测试成功
your_command |
awk '
/"interfaceId": "/{
gsub(/[^0-9]+|"\,/,"")
print
}
'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.