You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JQ将JSON存储的bash命令数组还原为多行字符串?

使用jq还原JSON中的bash命令为指定格式

当然可以用jq实现这个需求,核心思路是调整字符串缩进、去除多余换行并重新拼接成目标格式。

实现命令

假设你的JSON数据保存在文件commands.json中,执行以下jq命令即可得到目标格式:

jq -r '. | map(if index("newcert") then "  " + . else . end) | map(rtrimstr("\n")) | join("\n")' commands.json

命令解释

  1. . | map(if index("newcert") then " " + . else . end):遍历数组元素,给包含newcert的首行添加2个空格缩进,其余元素保持原有4个空格缩进不变。
  2. map(rtrimstr("\n")):移除每个元素末尾的换行符,避免拼接后出现多余空行。
  3. join("\n"):将处理后的所有元素用换行符连接,形成完整的多行命令字符串。
  4. -r参数:让jq输出原始字符串(而非JSON格式的带引号字符串)。

效果验证

输入的JSON数组:

[
  "newcert \\\n",
  "    --cn server1.acme.com \\\n",
  "    --san-dns server1.acme.com \\\n",
  "    --key-file ./config/key.pem \\\n",
  "    --csr-file ./config/csr.pem \\\n",
  "    --no-prompt \\\n"
]

执行命令后输出:

newcert \
      --cn server1.acme.com \
      --san-dns server1.acme.com \
      --key-file ./config/key.pem \
      --csr-file ./config/csr.pem \
      --no-prompt \

内容的提问来源于stack exchange,提问作者user1513388

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 18:31:01