Chris Edwards Chris Edwards - 6 months ago 8
Perl Question

Perl insert new line between every }{ match

I have a text file which contains a large amount of JSON objects and It hasn't been created with new lines or any separator between to the objects.

Currently I am using:

perl -e '$/ = "}{"; print "$_\n" while <>' file.txt > out.txt


But this causes malformed data as when the file gets split on new line the JSON objects will be missing the opening
{
as the new line gets placed after the
{
character.

Is there a way to insert the new line replacement between the
}{
match such as
}\n{
.

The file is quite large so I cant manually do it.

Doesn't have to be in Perl, can be in something more suited to the task.

Answer

Don't just print. Substitute the newline in between the } and {. The while needs a block now because the last s/// fails, so doing s/// && print while <> doesn't work.

$ cat json.json
{"foo":"bar"}{"bar":"baz"}{"bo":"shizzle"}
$ perl -e '$/ = "}{"; while (<>) { s/\}\{$/}\n{/; print; }' json.json 
{"foo":"bar"}
{"bar":"baz"}
{"bo":"shizzle"}
Comments