我正在尝试将以下命令的输出保存在脚本的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}"
答案 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创建