App-CSVUtils

 view release on metacpan or  search on metacpan

script/csv-sort  view on Meta::CPAN

ascending):

 name,age
 Dennis,15
 Andy,20
 Ben,30
 Jerry,30

Example output CSV (using C<--by-field -age>, which means by age numerically and
descending):

 name,age
 Ben,30
 Jerry,30
 Andy,20
 Dennis,15

Example output CSV (using C<--by-field name>, which means by name ascibetically
and ascending):

 name,age
 Andy,20
 Ben,30
 Dennis,15
 Jerry,30

Example output CSV (using C<--by-field ~name>, which means by name ascibetically
and descending):

 name,age
 Jerry,30
 Dennis,15
 Ben,30
 Andy,20

Example output CSV (using C<--by-field +age --by-field ~name>):

 name,age
 Dennis,15
 Andy,20
 Jerry,30
 Ben,30

You can also reverse the sort order (C<-r>) or sort case-insensitively (C<-i>).

For more flexibility, instead of C<--by-field> you can use C<--by-code>:

Example output C<< --by-code '$a-E<gt>[1] E<lt>=E<gt> $b-E<gt>[1] || $b-E<gt>[0] cmp $a-E<gt>[0]' >> (which
is equivalent to C<--by-field +age --by-field ~name>):

 name,age
 Dennis,15
 Andy,20
 Jerry,30
 Ben,30

If you use C<--hash>, your code will receive the rows to be compared as hashref,
e.g. `--hash --by-code '$a->{age} <=> $b->{age} || $b->{name} cmp $a->{name}'.

A third alternative is to sort using L<Sort::Sub> routines. Example output
(using C<< --by-sortsub 'by_lengthE<lt>rE<gt>' --key '$_-E<gt>[0]' >>, which is to say to sort by
descending length of name):

 name,age
 Dennis,15
 Jerry,30
 Andy,20
 Ben,30

If none of the C<--by-*> options are specified, the utility will bail unless
there's a default that can be used, e.g. when CSV has a single field then that
field will be used.

=head1 OPTIONS

C<*> marks required options.

=head2 Main options

=over

=item B<--by-code-json>=I<s>

Sort by using Perl code (JSON-encoded).

See C<--by-code>.

=item B<--by-code>=I<s>

Sort by using Perl code.

C<$a> and C<$b> (or the first and second argument) will contain the two rows to be
compared. Which are arrayrefs; or if C<--hash> (C<-H>) is specified, hashrefs; or
if C<--key> is specified, whatever the code in C<--key> returns.


=item B<--by-field>=I<s@>

Add a sort field specification.

Each field specification is a field name with an optional prefix. C<FIELD>
(without prefix) means sort asciibetically ascending (smallest to largest),
C<~FIELD> means sort asciibetically descending (largest to smallest), C<+FIELD>
means sort numerically ascending, C<-FIELD> means sort numerically descending.


Can be specified multiple times.

=item B<--by-fields-json>=I<s>

Sort by a list of field specifications (JSON-encoded).

See C<--by-field>.

=item B<--by-sortsub>=I<s>

Sort using a Sort::Sub routine.

When sorting rows, usually combined with C<--key> because most Sort::Sub routine
expects a string to be compared against.



( run in 0.373 second using v1.01-cache-2.11-cpan-d7a12ab2c7f )