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

如何用sed/awk移除文件中'"id": null'模式?现有sed命令无效

移除JSON中所有"id": null行的正确方法

我需要移除文件里所有包含"id": null的行,先后试了两条sed命令,命令能执行但文件内容完全没变化,求正确的解决办法。

原文件内容

{"objects": [
    {
        "version": "1a",
        "chromosome": "chr1",
                "id": null,
                "peptide": "123",
    },
    {
        "version": "1a",
        "chromosome": "chr1",
                "id": "This line has text and is printed.",
                "peptide": null,
    },
    {
        "version": '1a',
        "chromosome": "chr17",
                "id": null,
                "peptide": null}, 
                "id": 'This has text in it and this line is printed as well',
                "end": 460
            }
]
}

期望输出结果

{"objects": [
    {
        "version": "1a",
        "chromosome": "chr1",
        "peptide": "123",
    },
    {
        "version": "1a",
        "chromosome": "chr1",
                "id": "This line has text and is printed.",
                "peptide": null,
    },
    {
        "version": '1a',
        "chromosome": "chr17",
                "peptide": null}, 
                "id": 'This has text in it and this line is printed as well',
                "end": 460
            }
]
}

尝试过的sed命令

sed '/"id": *null/s/, [^,]*/ /' file --- if "id": null found substitute with blank up to the ending ,
sed -E "s/"id": *null, *//" file

正确解决办法

你之前的命令问题在于:要么试图替换行内内容而非删除整行,要么存在引号转义错误,且sed默认仅输出修改结果,不会直接修改原文件。

核心命令

如果要直接修改原文件,使用:

sed -i '/"id": *null/d' your_file.json
  • 说明:/"id": *null/匹配所有包含"id": null(中间允许任意空格)的行,d表示删除匹配到的行,-i选项让sed直接修改原文件。

如果只想预览修改结果、不改动原文件,去掉-i即可:

sed '/"id": *null/d' your_file.json

特殊情况处理

如果文件中存在单引号格式的'id': null,可以用兼容双引号和单引号的正则:

sed -i '/["'"'"']id["'"'"']: *null/d' your_file.json

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 12:20:36