use*_*r49 5 regex bash command-line json jq
[{
"Address": "The Sq"
},
{
"Address": "1 Bridge Rd"
}]
Run Code Online (Sandbox Code Playgroud)
使用以下 JSON,我如何使用 JQ 编写脚本来过滤正则表达式,其中我希望结果仅为以数字作为第一个字符的地址。我构建这个 JSON 使用
map({ Address: .[].payload.address })
Run Code Online (Sandbox Code Playgroud)
我如何添加到它来过滤我想要的正则表达式(即 \A[0-9])
虽然接受的答案有效,但我发现这更具可读性
$
$ echo '[{"Address": "The Sq", "n": 1}, {"Address": "1 Bridge Rd", "n": 2}]' | \
jq '.[] | .Address | select(.|test("^[0-9]"))'
"1 Bridge Rd"
$
$ echo '[{"Address": "The Sq", "n": 1}, {"Address": "1 Bridge Rd", "n": 2}]' | \
jq '.[] | select(.Address|test("^[0-9]"))'
{
"Address": "1 Bridge Rd",
"n": 2
}
$
Run Code Online (Sandbox Code Playgroud)
如果你想做一些不同的过滤:
$ echo '[{"name": "john doe", "sex": "male", "age": 26, "occupation": "city planner", "cod": "asphyxiation"}, {"name": "jane doe", "sex": "male", "age": 24, "occupation": "beautician", "cod": "strangulation"}, {"name": "crispy lips", "sex": "male", "age": 38, "occupation": "convicted killer"} ]' > in.json
$ cat in.json | jq .
[
{
"name": "john doe",
"sex": "male",
"age": 26,
"occupation": "city planner",
"cod": "asphyxiation"
},
{
"name": "jane doe",
"sex": "male",
"age": 24,
"occupation": "beautician",
"cod": "strangulation"
},
{
"name": "crispy lips",
"sex": "male",
"age": 38,
"occupation": "convicted killer"
}
]
$
Run Code Online (Sandbox Code Playgroud)
然后我们可以像这样进行基本的正则表达式过滤/转换:
$ cat in.json | jq '.[] | .name'
"john doe"
"jane doe"
"crispy lips"
$
$ cat in.json | jq '.[] | .name | select(.|test(".*doe"))'
"john doe"
"jane doe"
$
$ cat in.json | jq '.[] | select(.name|test(".*doe"))'
{
"name": "john doe",
"sex": "male",
"age": 26,
"occupation": "city planner",
"cod": "asphyxiation"
}
{
"name": "jane doe",
"sex": "male",
"age": 24,
"occupation": "beautician",
"cod": "strangulation"
}
$
$ cat in.json | jq '.[] | select(.name|test(".*doe")) | {n: .name, a: .age}'
{
"n": "john doe",
"a": 26
}
{
"n": "jane doe",
"a": 24
}
$
$
Run Code Online (Sandbox Code Playgroud)
如果您将以下过滤器添加到您已有的过滤器上,那么您将获得如下所示的输出:
map(select(.Address | test("^[0-9]")))
Run Code Online (Sandbox Code Playgroud)
输出:
[
{
"Address": "1 Bridge Rd"
}
]
Run Code Online (Sandbox Code Playgroud)
为了健壮性,您可能会考虑?在测试后添加:
map(select(.Address | test("^[0-9]")?))
Run Code Online (Sandbox Code Playgroud)
或者,您可以以map各种方式组合这两个调用。你可能想考虑:
.[].payload.address | select(test("^[0-9]")?) | {Address: .}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2991 次 |
| 最近记录: |