Perl在每个} {match之间插入新行

时间:2016-05-13 14:36:39

标签: json perl

我有一个包含大量JSON对象的文本文件,并且没有使用新行或对象之间的任何分隔符创建。

目前我正在使用:

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

但是这会导致格式错误的数据,因为当新文件在新行上拆分时,JSON对象将丢失开头{,因为新行将放在{字符之后。

有没有办法在}{匹配}\n{之间插入换行符。

文件非常大,所以我不能手动执行。

不必使用Perl,可以使用更适合任务的东西。

4 个答案:

答案 0 :(得分:7)

不要只是print。在}{之间替换换行符。 while现在需要一个阻止,因为上一个s///失败,因此执行s/// && print while <>不起作用。

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

答案 1 :(得分:2)

$ cat in.json
{"a":"b","c":"d"}{"e":"f","g":"h"}

$ perl -MJSON::XS -0777ne'
   my $parser = JSON::XS->new->utf8;
   $parser->incr_parse($_);
   while ( my $obj = $parser->incr_parse() ) {
      print( $parser->encode($obj), "\n" );
   }
' in.json
{"c":"d","a":"b"}
{"e":"f","g":"h"}

答案 2 :(得分:-1)

$ echo '{"a", "b", "c"}{42, "omg", "nyan"}{"no", "please", "stop"}' | perl -e '$/ = "}"; $\ = "}\n"; chomp and print while <>'
{"a", "b", "c"}
{42, "omg", "nyan"}
{"no", "please", "stop"}

答案 3 :(得分:-1)

您可以使用搜索和替换工具手动执行此操作。 例: 搜索 : ”}{” 替换为“} ^ p {”(在Word中,^是新行)