从返回的wget中获取数据

时间:2014-11-05 15:14:41

标签: json bash parsing grep

我正在编写一个与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来做,但无法做到正确。

4 个答案:

答案 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)

使用

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]}'
  1. 字段分隔符为:;
  2. 密钥始终位于最后一个字段中,在awk中使用$NF(字段数)访问此字段;
  3. split函数拆分$NF并根据仅为单个双引号字符的分隔符k将这些部分放在数组"\""中;
  4. k数组的第二个字段就是您想要的。