使用Unix工具提取字符串值

Ste*_*eve 0 unix linux perl awk json

我写了一个小的Perl脚本来从给定键名的JSON格式字符串中提取所有值(如下所示).因此,如果我将Perl脚本的命令行开关设置为id,那么它将从下面的JSON示例返回1,2和stringVal.这个脚本完成了这项工作,但我想看看其他人如何使用其他unix样式工具(如awk,sed或perl本身)来解决同样的问题.谢谢

{
   "id":"1",
   "key2":"blah"
},
{
   "id":"2",
   "key9":"more blah"
},
{
   "id":"stringVal",
   "anotherKey":"even more blah"
}
Run Code Online (Sandbox Code Playgroud)

摘录提取JSON值的perl脚本:

my @values;
while(<STDIN>) {
    chomp;
    s/\s+//g; # Remove spaces
    s/"//g; # Remove quotes
    push @values, /$opt_s:([\w]+),?/g; # $opt_s is a command line switch for the key to find
}

print join("\n",@values);
Run Code Online (Sandbox Code Playgroud)

Rob*_*Mah 5

我强烈建议使用JSON模块.它将在一个函数(和后面)中解析您的json输入.它还提供OOP接口.