public
Created

Convert csv to tsv with optional escaping.

  • Download Gist
csv2tsv
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
#!/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.csv\n";
 
exit main( @ARGV );
 
 
sub main
{
my $escape = 0;
 
GetOptionsFromArray( \@_, 'escape' => \$escape ) or die $usage;
 
my $csv = Text::CSV->new( { binary => 1 } );
my $in = \*STDIN;
 
while (my $row = $csv->getline( $in )) {
@$row = map c_escape($_) => @$row if $escape;
print join("\t" => @$row) . $/;
}
 
$csv->eof or $csv->error_diag();
 
return 0;
}
 
 
sub c_escape
{
my $str = shift;
my %escapes =
(
"\\" => "\\\\",
"\n" => "\\n",
"\t" => "\\t",
);
$str =~ s/([\\\n\t])/ $escapes{$1} /ge;
return $str;
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.