shell 如何用grep从Json中检索单个值?

v1uwarro  于 2023-01-21  发布在  Shell
关注(0)|答案(6)|浏览(292)

如何从给定的JSON中提取单个值?

{
  "Vpc": {
    "InstanceTenancy": "default", 
    "State": "pending", 
    "VpcId": "vpc-123", 
    "CidrBlock": "10.0.0.0/16", 
    "DhcpOptionsId": "dopt-123"
  }
}

尝试了此操作,但没有成功:

grep -e '(?<="VpcId": ")[^"]*'
sg3maiej

sg3maiej1#

您可能需要-Po,它与您的正则表达式一起工作:

$ grep -oP '(?<="VpcId": ")[^"]*' infile
vpc-123

如果GNU grep及其-P选项不可用,我们就不能使用look-arounds,而必须求助于例如使用grep两次:

$ grep -o '"VpcId": "[^"]*' infile | grep -o '[^"]*$'
vpc-123

第一个函数提取直到且不包括右引号,第二个函数从行尾开始搜索非引号。
但是,正如前面提到的,您最好正确地解析JSON。

jq的解决方案就像这样简单:

$ jq '.Vpc.VpcId' infile 
"vpc-123"

或者,获取原始输出而不是JSON:

$ jq -r '.Vpc.VpcId' infile 
vpc-123
x6h2sr28

x6h2sr282#

就像

grep '^ *"VpcId":' json.file \
  | awk '{ print $2 }' \
  | sed -e 's/,$//' -e 's/^"//' -e 's/"$//'
de90aj5v

de90aj5v3#

您可以:

sed -r -n -e '/^[[:space:]]*"VpcId":/s/^[^:]*: *"(.*)", *$/\1/p'

但实际上,使用任何shell工具在JSON内容上运行正则表达式都是一个坏主意。你应该考虑像python这样更明智的语言。

python -c 'import json, sys; print(json.loads(sys.stdin.read())["Vpc"]["VpcId"]);'
ylamdve6

ylamdve64#

尝试以下正则表达式模式:

\"VpcId\":\s?(\"\S+\")
y3bcpkx1

y3bcpkx15#

如果你能安装一个工具,我建议你使用jq jq,它允许非常简单的grep,并且对管道也有很好的支持。

baubqpgj

baubqpgj6#

OP请求使用grep的解决方案。如果他的意思是使用terminal,则节点cli是一个替代方案,因为对JSON的支持是完全的。一个替代方案可以是命令node --eval“script”

echo '{"key": 42}' \
| node -e 'console.log(JSON.parse(require("fs").readFileSync(0).toString()).key)' //prints 42

相关问题