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

如何用jq从其他文本文件读取内容更新JSON文件?

问题需求与更新

初始需求

我有多个文本文件,每个文件内包含一个标题,示例创建命令如下:

echo 'title: hello' > 1.txt
echo 'title: world' > 2.txt
echo 'title: good' > 3.txt

同时存在一个Shell脚本生成的JSON文件abc.json,内容如下:

{
  "": [
    {
      "title": "",
      "file": "1"
    },
    {
      "title": "",
      "file": "2"
    },
    {
      "title": "",
      "file": "3"
    }
  ]
}

需要将abc.json中的title值替换为对应文本文件中的标题,更新后效果如下:

{
  "": [
    {
      "title": "hello",
      "file": "1"
    },
    {
      "title": "world",
      "file": "2"
    },
    {
      "title": "good",
      "file": "3"
    }
  ]
}

所有文本文件与JSON文件位于同一目录:

➜  tmp.uFtH6hMC ls
1.txt    2.txt    3.txt    abc.json

更新后的详细需求

之前的需求描述有遗漏,补充以下关键细节:

  • 文本文件名可能包含空格,当前目录结构如下:
➜  $ gfind . -maxdepth 1 -type f -printf '%P
'
The text file contain one title line and more content.txt
The title identifier in the text file is fixed.txt
The filename of text file may contain space.txt
abc.json
  • 文本文件中存在一行标题行(可位于文件任意位置),格式为## <title-value>,其中##是固定的标题标识符,与标题值之间用单个空格分隔,需要提取该行的标题值填入abc.json的title字段。示例文件内容:
    • The text file contain one title line and more content.txt:
    ## hello world
    some more content below...
    ...
    
    • The title identifier in the text file is fixed.txt:
    ## How are you?
    some more content below...
    ...
    
    • The filename of text file may contain space.txt:
    some pre-content...
    ...
    
    ## I'm fine, thank you.
    
    some more content below...
    ...
    
  • 更新前abc.json内容:
{
  "": [
    {
      "title": "",
      "file": "The filename of text file may contain space"
    },
    {
      "title": "",
      "file": "The text file contain one title line and more content"
    },
    {
      "title": "",
      "file": "The title identifier in the text file is fixed"
    }
  ]
}
  • 更新后abc.json预期效果:
{
  "": [
    {
      "title": "I'm fine, thank you.",
      "file": "The filename of text file may contain space"
    },
    {
      "title": "hello world",
      "file": "The text file contain one title line and more content"
    },
    {
      "title": "How are you?",
      "file": "The title identifier in the text file is fixed"
    }
  ]
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 16:41:32