title: Remove trailing json comma with command line tools
body: <p>I want to remove trailing comma from json as,</p>
  
  <pre><code>{
    "key1": "value1",
    "object": {
      "key2": "value2", // &lt;- remove comma
    },
    "key3": "value3", // &lt;- remove comma
  }
  </code></pre>
  
  <p>I came up with,</p>
  
  <pre><code>tr -d '\n' | \
  sed -E 's:,(\s*}):\1:g' | \
  jq .
  </code></pre>
  
  <p>and it works but I want to get this fully in <code>sed</code>.</p>
  
  <p>I came up with,</p>
  
  <pre><code>sed -E '/,\s*$/ { N; s:,\s*(\n\s*},?):\1: }'
  </code></pre>
  
  <p>which works for above input but fails for</p>
  
  <pre><code>{
    "key1": "value1",
    "object": {
      "key2": "value2",
    },
    "key3": "value3",
    "key4": "value4", // &lt;- remove comma
  }
  </code></pre>
  
  <p>as <code>N</code> reads the next line and starts over from the line after next.</p>
  
  <pre><code>// output sed -E '/,\s*$/ { N;l }' using l/look command
  {
    "key1": "value1",\n  "object": {$
    "key1": "value1",
    "object": {
      "key2": "value2",\n  },$
      "key2": "value2",
    },
    "key3": "value3",\n  "key4": "value4",$
    "key3": "value3",
    "key4": "value4",
  }
  </code></pre>
  
  <p><strong>Update:</strong></p>
  
  <p>Adding another example for testing:</p>
  
  <pre><code>{
    "key1": "value1",
    "object1": {
      "object2": {
        "key2": "value2"
      },
    },
    "key3": "value3",
  }
  </code></pre>
  
  <p><strong>Update:</strong></p>
  
  <p>This is working for whatever I've thrown at it. </p>
  
  <pre><code>sed -E -n 'H; x; s:,(\s*\n\s*}):\1:; P; ${x; p}' | \
      sed '1 d'
  </code></pre>
  
  <p>Explanation:</p>
  
  <pre><code>sed -E -n 'H; x; P; ${x; p}'
  </code></pre>
  
  <p><code>-n 'H; x'</code> to get every line appended to the next line in pattern space (except for the last line which is simply printed with <code>${x; p}</code>)</p>
  
  <p>and</p>
  
  <pre><code>s:,(\s*\n\s*}):\1:;
  </code></pre>
  
  <p>to remove the trailing comma in the pattern space.</p>