【问题标题】:Can you use sed to delete lines based on multiple conditions?您可以使用 sed 根据多个条件删除行吗?
【发布时间】:2026-02-10 09:50:01
【问题描述】:

所以我有一个 JSON 文件,其中包含我不想要的行。

我想删除所有有的行

"Voice": "No"

但是有两个条件。例如,下面给出的文件

{
            "start": 0.0,
            "end": 3.33,
            "segmentId": "00001",
            "primaryType": "Noise",
            "loudnessLevel": "Normal",
            "Voice": "No"
         },

我希望它是

{
            "start": 0.0,
            "end": 3.33,
            "segmentId": "00001",
            "primaryType": "Noise",
            "loudnessLevel": "Normal"
         },

Normal 之后的, 被删除,以便 JSON 文件结构保持不变。

然而,另一方面,

{
            "start": 4.01,
            "end": 13.52,
            "language": "ja",
            "speakerId": "sss",
            "transcriptionData": {
               "content": "content"
            },
            "Voice": "No",
            "segmentLanguages": [
               "j"
            ]
         },

会变成

{
            "start": 4.01,
            "end": 13.52,
            "language": "ja",
            "speakerId": "sss",
            "transcriptionData": {
               "content": "content"
            },
            "segmentLanguages": [
               "j"
            ]
         },

上面的, 保持不变以保持 JSON 格式。

我尝试过sed -i 's/"Voice": "No"/d,但由于缺乏经验,结果适得其反。有没有办法做到这一点?

【问题讨论】:

  • 为什么是 sed 而不是 jq? Sed 不理解 JSON 格式。
  • 你有jq或者可以安装吗?

标签: json bash shell sed


【解决方案1】:

您不会使用 sed 来完成这项工作,而是使用 jq:

$ jq 'del(.Voice)' sample1

您的数据的准确输出:

{
  "start": 0,
  "end": 3.33,
  "segmentId": "00001",
  "primaryType": "Noise",
  "loudnessLevel": "Normal"
}
parse error: Expected value before ',' at line 8, column 11

但如果你坚持使用 sed,应该这样做:

$ sed ':a;N;$!ba;s/,\n *"Voice": "No"//g' sample2

输出:

{
            "start": 4.01,
            "end": 13.52,
            "language": "ja",
            "speakerId": "sss",
            "transcriptionData": {
               "content": "content"
            },
            "segmentLanguages": [
               "j"
            ]
         },

我会使用 jq。

【讨论】:

    【解决方案2】:

    当你不想使用jq(made for json)时,可以使用

    sed -zr 's/,\s+"Voice": "No"//' inputfile
    

    这仅在您确定在 Voice 行之前有一行带有 , 时才有效。

    【讨论】:

      最近更新 更多