转义jq查询并将输出保存在bash变量中

时间:2018-07-27 20:08:57

标签: bash jq

我正在尝试将以下命令的输出保存在脚本的bash变量中。但是无论我怎么努力,我都无法正确地排除引号。

这是我要将其输出保存在变量中的命令。

$ echo '[{"field":"fieldA","bucket":["a","b","c"]},{"field":"fieldB","bucket":["a","b","c","d"]}]' | jq -r '.[]|{field, bucketText: .bucket|join(", ")}|join(" found in bucket: ")'
fieldA found in bucket: a, b, c
fieldB found in bucket: a, b, c, d

这是我在脚本文件中的尝试

#!/bin/bash

INPUT='[{"field":"fieldA","bucket":["a","b","c"]},{"field":"fieldB","bucket":["a","b","c","d"]}]'

OUTPUT_LINES="$(echo ${INPUT} | jq -r '.[]|{field, bucketText: .bucket|join(\", \")}|join(\" found in bucket: \")')"

printf "%s\n" "${OUTPUT_LINES}"

1 个答案:

答案 0 :(得分:0)

您可以使用以下脚本:

#!/bin/bash

input='[{"field":"fieldA","bucket":["a","b","c"]},{"field":"fieldB","bucket":["a","b","c","d"]}]'

output="$(jq -r '.[]|{field, bucketText: .bucket|join(", ")}|join(" found in bucket: ")' <<< "$input")"

printf "%s\n" "$output"

输出:

fieldA found in bucket: a, b, c
fieldB found in bucket: a, b, c, d

建议的更改:

  • 无需在单引号jq命令中转义双引号
  • 建议使用小写变量而不是全部大写
  • 避免使用流水线,并在jq命令中使用here-string以避免不必要的子shell创建