我正在编写一个与badips.com一起使用的bash脚本
此命令:
wget https://www.badips.com/get/key -qO -
会返回这样的内容:
{"err":"","suc":"new key 5f72253b673eb49fc64dd34439531b5cca05327f has been set.","key":"5f72253b673eb49fc64dd34439531b5cca05327f"}
或者像这样:
{"err":"","suc":"Your Key was already present! To overwrite, see http:\/\/www.badips.com\/apidoc.","key":"5f72253b673eb49fc64dd34439531b5cca05327f"}
我需要将键值解析出来(5f72253b673eb49fc64dd34439531b5cca05327f
)到脚本中的变量中。我更愿意使用grep
来做,但无法做到正确。
答案 0 :(得分:3)
不是使用某些grep
进行解析,而是拥有完美的工具:jq
。
请参阅:
jq '.key' file
或
.... your_commands .... | jq '.key'
将返回
"5f72253b673eb49fc64dd34439531b5cca05327f"
请参阅另一个示例,例如获取suc
属性:
$ cat a
{"err":"","suc":"new key 5f72253b673eb49fc64dd34439531b5cca05327f has been set.","key":"5f72253b673eb49fc64dd34439531b5cca05327f"}
{"err":"","suc":"Your Key was already present! To overwrite, see http:\/\/www.badips.com\/apidoc.","key":"5f72253b673eb49fc64dd34439531b5cca05327f"}
$ jq '.suc' a
"new key 5f72253b673eb49fc64dd34439531b5cca05327f has been set."
"Your Key was already present! To overwrite, see http://www.badips.com/apidoc."
答案 1 :(得分:0)
你可以尝试下面的grep命令,
grep -oP '"key":"\K[^"]*(?=")' file
答案 2 :(得分:0)
使用perl:
wget https://www.badips.com/get/key -qO - |
perl -MJSON -MFile::Slurp=slurp -le '
my $s = slurp "/dev/stdin";
my $d = JSON->new->decode($s);
print $d->{key}
'
不像先例那样强大,但不需要安装新模块,股票perl
可以做到:
wget https://www.badips.com/get/key -qO - |
perl -lne 'print $& if /"key":"\K[[:xdigit:]]+/'
答案 3 :(得分:0)
awk
保持简单
wget ... - | awk -F: '{split($NF,k,"\"");print k[2]}'
:
; awk
中使用$NF
(字段数)访问此字段; split
函数拆分$NF
并根据仅为单个双引号字符的分隔符k
将这些部分放在数组"\""
中; k
数组的第二个字段就是您想要的。