Created
October 22, 2012 09:06
-
-
Save netfeed/3930511 to your computer and use it in GitHub Desktop.
Print specified, or all, columns from a CSV-file
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; | |
| 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, | |
| ); | |
| if ($print_help) { | |
| print STDOUT "csvcolumns [--delimiter=,] [--binary] [--output-delimiter=\\t] file [columns...]\n"; | |
| exit 0; | |
| } | |
| my $filename = shift @ARGV; | |
| if (!$filename || !(-e $filename)) { | |
| print STDERR "no file supplied\n" ; | |
| exit 1; | |
| } | |
| 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