【问题标题】:jq : how can i use the same search in other field without duplicate code?jq:如何在其他字段中使用相同的搜索而不重复代码?
【发布时间】:2021-02-10 10:51:53
【问题描述】:

我有这个 jq 命令:

cat myfile | jq  -c '{ 
    domain: .name, 
    results: .data | select(.answers != null) | .answers | map(.answer) | del(.[] | nulls) , 
    includes: .data | select(.answers != null) | .answers | map(.answer) | del(.[] | nulls) | map(match("rearch:(.*?)?[ \"]"; "ig").captures[0].string) | unique
    }'

得到这个结果:

{"domain":"blabla.com","results":["dorem rearch:blble.k iyh"],"includes":["blble.k"]}
{"domain":"bla.com","results":["koa rearch:ble.m","kl rearch:be.c lk"],"includes":["ble.m","be.c"]}

我的问题是:有没有办法DRY我的命令?
我的意思是如何在没有 duplicate 部分的情况下获得 相同的结果

.数据 |选择(.answers != null) | .答案 |地图(.answer) |德尔(。[] | 空)

如何重用results feild 的结果?
我有一个非常大的文件要处理,所以我不想浪费时间和资源。

【问题讨论】:

  • 您可以粘贴输入 JSON 并显示预期的 exact 输出吗?很难提供替代方案,但只是看看你的尝试

标签: json duplicates field jq


【解决方案1】:

带变量

< myfile.json jq  -c '
  (.data | select(.answers != null) | .answers | map(.answer) | del(.[] | nulls)) as $data
  | { 
    domain: .name, 
    results: $data,
    includes: $data | map(match("rearch:(.*?)?[ \"]"; "ig").captures[0].string) | unique
    }
'

没有变量

< myfile.json jq  -c '
  { domain: .name, 
    results: (.data | select(.answers != null) | .answers | map(.answer) | del(.[] | nulls)) }
  | .includes = (.results | map(match("rearch:(.*?)?[ \"]"; "ig").captures[0].string) | unique)
'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-14
    • 2015-01-11
    • 2017-10-02
    • 2022-12-06
    • 2016-06-22
    • 1970-01-01
    • 2020-02-22
    • 1970-01-01
    相关资源
    最近更新 更多