根据特定列对CSV排序? [英] Sort CSV based on a certain column?

查看:186
本文介绍了根据特定列对CSV排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确定我过去已经这样做过,但我忘记了一些小东西,但是如何在特定列上对CSV文件进行排序?我对有无第3方Perl模块的答案感兴趣.主要是没有方法,因为我并不总是有权安装其他模块.

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 without 3rd party Perl modules. Mainly methods without, since I don't always have access to install additional modules.

示例数据:

name,25,female
name,24,male
name,27,female
name,21,male

在第二个数字列上排序后所需的最终结果:

desired end result after sorting on the 2nd numeric column:

name,21,male
name,24,male
name,25,female
name,27,female

推荐答案

由于CSV是一种非常复杂的格式,因此最好使用为我们完成工作的模块.

As CSV is a pretty complex format, it is better to use a module that does the work for us.

以下是使用 Text :: CSV 模块的示例:

Following is an example using the Text::CSV module:

#!/usr/bin/env perl

use strict;
use warnings;

use constant AGE => 1;

use Text::CSV;

my $csv = Text::CSV->new();

my @rows;
while ( my $row_ref = $csv->getline( \*DATA ) ) {
    push @rows, $row_ref;
}

@rows = sort { $a->[AGE] <=> $b->[AGE] } @rows;

for my $row_ref (@rows) {
    $csv->combine(@$row_ref);
    print $csv->string(), "\n";
}

__DATA__
name,25,female
name,24,male
name,27,female
name,21,male

这篇关于根据特定列对CSV排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆