public
Last active

Convert tsv to csv with optional unescaping.

  • Download Gist
tsv2csv
Perl
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
#!/usr/bin/env perl
 
use Text::CSV;
use Getopt::Long qw/ GetOptionsFromArray :config pass_through /;
use warnings;
use strict;
 
my $usage = "usage: $0 [-e] < file.tsv\n";
 
exit main( @ARGV );
 
 
sub main
{
my $escape = 0;
 
GetOptionsFromArray( \@_, 'escape|e' => \$escape ) or die $usage;
 
my $csv = Text::CSV->new( { binary => 1 } );
my $out = \*STDOUT;
 
while (<STDIN>)
{
chomp;
do { print $/; next } if /^\s*$/;
my @row = split /\t/;
@row = map c_unescape($_) => @row if $escape;
$csv->combine( @row ) or die "CSV error: ".$csv->error_diag;
print $out $csv->string.$/;
}
 
return 0;
}
 
 
sub c_unescape
{
my $str = shift;
my %unescapes =
(
"\\\\" => "\\",
"\\n" => "\n",
"\\t" => "\t",
);
$str =~ s/(\\[\\nt])/ $unescapes{$1} /ge;
return $str;
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.