#!/bin/sh exec ${PERL-perl} -Sx $0 ${1+"$@"} #!perl # sum-rows --- add selected columns in rows and print result # Copyright (C) 2002 Noah S. Friedman # Author: Noah Friedman # Created: 2002-08-26 # $Id: sum-rows,v 1.1 2002/08/27 02:25:08 friedman Exp $ # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, you can either send email to this # program's maintainer or write to: The Free Software Foundation, # Inc.; 59 Temple Place, Suite 330; Boston, MA 02111-1307, USA. # Commentary: # This script takes as input a table of numbers and adds all the values in # each column together, printing the sum for each column. # Code: use Getopt::Long; use strict; sub usage () { $0 =~ s|.*/||; print "Usage: $0 {options} [files {...}]\n Options are: -h, --help You're looking at it. -c, --column C0,C1,... Just sum columns C0, C1, ... This option may be specified more than once. -s, --separator SEP Field separator between columns. This can be any regular expression. The default field separator is any number of tabs and spaces, i.e. \"[ \\t]+\". -S, --output-separator SEP Output separator between fields. Default \" \". -w, --skip-leading-whitespace Skip leading whitespace before splitting fields. This option is probably only useful in conjunction with the default separator regexp.\n"; exit (1); } sub main { my $insep = "[ \t]+"; my $outsep = " "; my @cols; my %col; my $skip_lwspace = 0; Getopt::Long::config ('bundling', 'autoabbrev'); GetOptions ("s|separator=s", \$insep, "S|output-separator=s", \$outsep, "c|column=s@", \@cols, "w|skip-leading-whitespace", \$skip_lwspace, "h|help", \&usage); map { $col{$_} = 1 } split (/\s*,\s*/o, join (",", @cols)); my @sum; while (<>) { s/^\s+/$1/o if $skip_lwspace; my @row = split (/$insep/o, $_); for (my $i = 0; $i < scalar @row; $i++) { next if (%col && !exists $col{$i}); $sum[$i] += $row[$i]; } } if (%col) { print join ($outsep, map { $sum[$_] } keys %col), "\n"; } else { print join ($outsep, @sum), "\n"; } } main (); # local variables: # mode: perl # eval: (auto-fill-mode 1) # end: # sum-rows ends here