gpt4 book ai didi

json - grep 键名的 json 值。 (没有选项-P的busybox)

转载 作者:太空狗 更新时间:2023-10-29 11:49:35 26 4
gpt4 key购买 nike

我发现有很多讨论“如何 grep json 值”的话题。但不幸的是,对我和所有从 busybox(嵌入式 linux)使用 grep 的人来说都没用。这个 grep 版本没有选项“-P”(perl exp)。只有“-E”(扩展正则表达式)可用。

BusyBox v1.20.2 () multi-call binary.

Usage: grep [-HhnlLoqvsriwFE] [-m N] [-A/B/C N] PATTERN/-e PATTERN.../-f FILE [FILE]...

Search for PATTERN in FILEs (or stdin)

-H Add 'filename:' prefix
-h Do not add 'filename:' prefix
-n Add 'line_no:' prefix
-l Show only names of files that match
-L Show only names of files that don't match
-c Show only count of matching lines
-o Show only the matching part of line
-q Quiet. Return 0 if PATTERN is found, 1 otherwise
-v Select non-matching lines
-s Suppress open and read errors
-r Recurse
-i Ignore case
-w Match whole words only
-x Match whole lines only
-F PATTERN is a literal (not regexp)
-E PATTERN is an extended regexp
-m N Match up to N times per file
-A N Print N lines of trailing context
-B N Print N lines of leading context
-C N Same as '-A N -B N'
-e PTRN Pattern to match
-f FILE Read pattern from file

我有一个 json 例子:

{
"one": "apple",
"two": "banana"
}

现在,我想提取值,例如键“一”的“苹果”。

grep -E '".*?"' file.json

只是一个例子,它应该是什么样子。

顺便说一句:如何从正则表达式访问组?

如果有任何帮助或替代方案,我将不胜感激。

最佳答案

使用busybox awk:

busybox awk  -F '[:,]' '/"one"/ {gsub("[[:blank:]]+", "", $2); print $2}'
  • -F '[:,]' 设置字段分隔符为:,

  • /"one"/{gsub("[[:blank:]]+", "", $2);如果该行包含 "one",则打印 $2} macthes,如果是,则从第二个字段中去除所有水平空白,然后打印该字段

如果你也想去掉引号:

busybox awk  -F '[:,]' '/"one"/ {gsub("[[:blank:]\"]+", "", $2); print $2}'

示例:

$ cat file.json 
{
"one": "apple",
"two": "banana"
}

$ busybox awk -F '[:,]' '/"one"/ {gsub("[[:blank:]]+", "", $2); print $2}' file.json
"apple"

$ busybox awk -F '[:,]' '/"one"/ {gsub("[[:blank:]\"]+", "", $2); print $2}' file.json
apple

关于json - grep 键名的 json 值。 (没有选项-P的busybox),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45025713/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com