Sort CSV based on a certain column?

前端 未结 7 960
自闭症患者
自闭症患者 2020-12-18 09:50

I\'m sure I\'ve done this in the past and there is something small I\'m forgetting, but how can I sort a CSV file on a certain column? I\'m interested in answers with and wi

7条回答
  •  情书的邮戳
    2020-12-18 10:48

    I would do something like this:

    #!/usr/bin/perl
    use warnings;
    use strict;
    
    my @rows = map { chomp; [split /[,\s]+/, $_] } ; #read each row into an array
    my @sorted = sort { $a->[1] <=> $b->[1] } @rows; # sort the rows (numerically) by second column
    
    for (@sorted) {
      print join(', ', @$_) . "\n"; # print them out as CSV
    }
    
    __DATA__
    name,25,female
    name,24,male
    name,27,female
    name,21,male
    

提交回复
热议问题