Created
April 4, 2013 17:14
-
-
Save acg/5312217 to your computer and use it in GitHub Desktop.
Convert csv to tsv with optional escaping.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment