#!/usr/bin/perl -w use strict; my $cols_per_row = 6; # columns per row undef $/; my $table = ; 1 while(chomp); my @table = ( [] ); my $cols_got = 0; while ($table ne '') { $table =~ s{^,?(["']?)((?:[^\1]|\1(?=\1))+?)?(\1)[,\n]}{}s; if (++$cols_got > $cols_per_row) { push @table, []; $cols_got = 1; } push @{$table[-1]}, $2; } foreach my $row (@table) { foreach my $col (@$row) { $col =~ s/(["']){2}/$1/g; $col =~ s/\n/\\n/g; } print join('|', @$row), "\n"; } __DATA__ 12345,"foobar",45.67,"""this"" is a field with embedded newlines",4567,"frumpy" 12345,"foobar",45.67,"this is a ""field"" with embedded newlines",4567,"frumpy"