简体   繁体   中英

Perl - count number of columns per row in a csv file

I want to count the number of columns in a row for a CSV file.

row 1 10 columns
row 2 11 columns etc.

I can print out the value of the last column, but I really just want a count per row.

perl -F, -lane "{print @keys[$_].$F[$_] foreach(-1)}" < testing.csv

I am on a windows machine

Thanks.

If you have a proper csv file, it can contain embedded delimiters (eg 1,"foo,bar",2 ), in which case a simple split will not be enough. You can use the Text::CSV module fairly easily with a one-liner like this:

Copy/paste version:

perl -MText::CSV -lwe"my $c=Text::CSV->new({sep_char=>','}); while($r=$c->getline(*STDIN)) { print scalar @$r }" < sorted.csv

Readable version:

perl -MText::CSV            # use Text::CSV module
     -lwe                   # add newline to print, use warnings
         "my $c = Text::CSV->new();             # set up csv object 
          while( $r = $c->getline(*STDIN) ) {   # get lines from stdin
              print scalar @$r                  # print row size
          }" < sorted.csv                       # input file to stdin

If your input can be erratic, Text::CSV->getline might choke on corrupted lines (the while loop is ended), in which case it may be safer to use plain parsing:

perl -MText::CSV -nlwe"
    BEGIN { $r = Text::CSV->new() }; 
    $r->parse($_); 
    print scalar $r->fields
" comma.csv

Note that in this case we use a different input method. This is because while getline() requires a file handle, parse() does not. Since the diamond operator uses either ARGV or STDIN depending on your argument, I find it is better to be explicit.

If you don't have commas as part of the fields, you can split the line and count the number of fields

#! /usr/bin/perl

use strict;
use warnings;

my @cols = split(',', $_);
my $n = @cols;
print "row $. $n columns\n";

you can call this

perl -n script.pl testing.csv

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM