This question already has an answer here:
这个问题在这里已有答案:
- Parsing JSON with Unix tools 33 answers
- 用Unix工具解析JSON 33答案
Inside my bash script I've created a function that returns the following JSON array:
在我的bash脚本中,我创建了一个返回以下JSON数组的函数:
{
"access_token": "sjdhjdYdjsdbhggjhSJ78dbdsdbMhd=",
"scopes": "repository:delete repository:admin repository:write project:write team:write account:write",
"expires_in": 3600,
"refresh_token": "skdjKJDJDBNBDs",
"token_type": "bearer"
}
Now I wan't to grep the access token between the "". So I got sjdhjdYdjsdbhggjhSJ78dbdsdbMhd=
现在我不想在“”之间grep访问令牌。所以我得到了sjdhjdYdjsdbhggjhSJ78dbdsdbMhd =
I've created a regex like below but this returns a grep: invalid repetition count(s)
error.
我已经创建了一个如下所示的正则表达式,但这会返回一个grep:无效的重复计数错误。
grep -P '\{\s*"access_token"\s*:\s*(.+?)\s*\"' foobar.txt
1 个解决方案
#1
1
Since you're dependending on nonstandard, nonportable functionality (in the form of grep -P
), you might as well switch to a tool that's built for the job at hand (and actually understands JSON syntax, so it'll work even if your input has, say, a newline between the key and value, so long as it's syntactically valid):
由于您依赖于非标准的,不可移植的功能(以grep -P的形式),您也可以切换到为手头的工作构建的工具(并且实际上理解JSON语法,因此即使您的工作也是如此例如,输入有一个键和值之间的换行符,只要它在语法上有效):
jq -r .access_token <foobar.txt
#1
1
Since you're dependending on nonstandard, nonportable functionality (in the form of grep -P
), you might as well switch to a tool that's built for the job at hand (and actually understands JSON syntax, so it'll work even if your input has, say, a newline between the key and value, so long as it's syntactically valid):
由于您依赖于非标准的,不可移植的功能(以grep -P的形式),您也可以切换到为手头的工作构建的工具(并且实际上理解JSON语法,因此即使您的工作也是如此例如,输入有一个键和值之间的换行符,只要它在语法上有效):
jq -r .access_token <foobar.txt