带引号的狡猾的grep&输入中的括号(json响应)

时间:2014-05-20 21:38:26

标签: json bash curl

我试图从bash脚本中的json响应中提取出数字(时间戳)模式:

以下是代码段>

 response=$(curl -isb -H "Accept: application/json" http://host:5000/app?q=1)
 #response=$(wget -q -O - http://host:5000/app?q=1)
 echo "Response : $response"
 latest=$(echo $response | grep -oP "[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]{1,}")
 echo "Latest version is : $latest"

然而,当我运行测试时,grep的输出为空

Response : HTTP/1.1 200 OK
Content-Type: application/json
X-Content-Type-Options: nosniff
Set-Cookie: rack.session=BAh7CEkiD3Nlc3Npb25faWQGOgZFVEkiRTMyYWM2NGJjNzBhMDczYWQ5ZDcz%0AMDQ4MjA2ZjYwMzY4NDMxMzhmYTEwY2Q2MDEwMmU5NjA0YmY4MDBmNmRhZDQG%0AOwBGSSIJY3NyZgY7AEZJIiU4OTAyMDk4MDcxOTM5MWY1MmMzMzZlZjhiNjNi%%%0ABjsARkkiGUhUVFBfQUNDRVBUX0xBTkdVQUdFBjsAVEkiLWRhMzlhM2VlNWU2%0AYjRiMGQzMjU1YmZlZjk1NjAxODkwYWZkODA3MDkGOwBG%0A--3d18f21cd9851f99ff05b45556a78988132221c9; path=/; HttpOnly
Content-Length: 40

["env-svr-app-mod-2014-05-15-155"]
Latest version is :

因此curl输出中包含时间戳。 我期待在输出中看到2014-05-15-155。

我尝试了几种不同的选项(和wget),但看起来我在这里遗漏了一些明显的东西。

curl输出本身的qupts / bracket / new行是否会导致问题? (我记得有几次看到这项工作)

欣赏轻推! THX。

2 个答案:

答案 0 :(得分:1)

尝试使用grep引用$response。 bash倾向于将换行符转换为空格。

答案 1 :(得分:0)

将grep命令替换为:

perl -lne '/\w+-(\d+-.*)"/ && print $1'

例如:

[root@TIAGO-TEST tmp]# cat response 
HTTP/1.1 200 OK
Content-Type: application/json
X-Content-Type-Options: nosniff
Set-Cookie: rack.session=BAh7CEkiD3Nlc3Npb25faWQGOgZFVEkiRTMyYWM2NGJjNzBhMDczYWQ5ZDcz%0AMDQ4MjA2ZjYwMzY4NDMxMzhmYTEwY2Q2MDEwMmU5NjA0YmY4MDBmNmRhZDQG%0AOwBGSSIJY3NyZgY7AEZJIiU4OTAyMDk4MDcxOTM5MWY1MmMzMzZlZjhiNjNi%%%0ABjsARkkiGUhUVFBfQUNDRVBUX0xBTkdVQUdFBjsAVEkiLWRhMzlhM2VlNWU2%0AYjRiMGQzMjU1YmZlZjk1NjAxODkwYWZkODA3MDkGOwBG%0A--3d18f21cd9851f99ff05b45556a78988132221c9; path=/; HttpOnly
Content-Length: 40

["env-svr-app-mod-2014-05-15-155"]
[root@TIAGO-TEST tmp]# cat response| perl -lne '/\w+-(\d+-.*)"/ && print $1'
2014-05-15-155