Chris Edwards Chris Edwards - 8 months ago 14
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

Is there a way to insert the new line replacement between the
match such as

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.


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
$ perl -e '$/ = "}{"; while (<>) { s/\}\{$/}\n{/; print; }' json.json