skip to Main Content

I’m trying to parse some JSON and am running into an issue with parsing. My objects are:

{ 
  "foo" : "bar"
}
{
  "spam" : "ham"
}

I want to change this in a shell script to:

{ 
  "foo" : "bar"
},
{
  "spam" : "ham"
}

I’ve tried:

sed 's/}n{/},n{/g' file.json > file.json.tmp

and solutions like Replace curly braces separated by a newline with sed But without any progress. Any clue what I am missing here?

2

Answers


  1. Using perl is easier :

    perl -0777 -pe 's/}n{/},n{/g' file.json > file.json.tmp
    

    Or if you have gnu-sed :

    sed ':a;N;$!ba;s/}n[{]/},n{/g' file.json > file.json.tmp
    
    Login or Signup to reply.
  2. Using GNU sed for -z to read the whole input into memory at once as a single multi-line record:

    $ sed -z 's/}n{/},n{/g' file
    {
      "foo" : "bar"
    },
    {
      "spam" : "ham"
    }
    

    or doing the same using any awk in any shell on every Unix box:

    $ awk '{r=(NR>1 ? r RS : "") $0} END{$0=r; gsub(/}n{/,"},n{"); print}' file
    {
      "foo" : "bar"
    },
    {
      "spam" : "ham"
    }
    

    The default sed on MacOS is BSD, not GNU, so the above sed command won’t work unless you install GNU sed. The awk command will work on MacOS or anywhere else.

    Your sed command in the question couldn’t find n in the string it’s working on because sed works on 1 n-separated string at a time by default and so the string it’s working on can’t contain n as it’s separated from the previous and next strings by n.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search