Last active
December 19, 2015 21:19
-
-
Save netfeed/6019715 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 strict; | |
| use warnings; | |
| # apt-get install libtext-csv-xs-perl | |
| use Getopt::Long; | |
| use Text::CSV_XS; | |
| my $delimiter = ','; | |
| my $binary = 0; | |
| my $output_delimiter = "\t"; | |
| my $print_help = 0; | |
| my $result = GetOptions('delimiter=s' => \$delimiter, | |
| 'binary' => \$binary, | |
| 'output-delimiter=s' => \$output_delimiter, | |
| 'help' => \$print_help, | |
| ); | |
| my $filename = shift @ARGV; | |
| if (!$filename || !(-e $filename)) { | |
| $print_help = 1; | |
| } | |
| if ($print_help) { | |
| print STDOUT "csvcolumns [--delimiter=,] [--binary] [--output-delimiter=\\t] file [columns...]\n"; | |
| exit 0; | |
| } | |
| my $csv = Text::CSV_XS->new({ sep_char => $delimiter, binary => $binary }); | |
| open my $fh, "<", $filename; | |
| my @keys = @{ $csv->getline($fh) }; | |
| my $columns = scalar @ARGV ? \@ARGV : \@keys; | |
| while (my $csv_row = $csv->getline($fh)) { | |
| last unless defined $csv_row and scalar @{ $csv_row }; | |
| my %row; | |
| @row{@keys} = @$csv_row; | |
| my @cols = (); | |
| for my $key (@{ $columns }) { | |
| push @cols, $row{$key}; | |
| } | |
| print STDOUT sprintf("%s\n", join($output_delimiter, @cols)) if scalar @cols; | |
| } | |
| close $fh; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment