Category: Utility Scripts
Author/Contact Info Stephen Flitman <sflitman at>
Description: A simple text-based column extractor for use in Unix pipelines
# Stephen Flitman - extract one or more columns of a table
# Released under GPLv2
# Usage: ... | xcol N M ...
# where N, M, ... are 0-based column indices, and columsn are split by
+ tabs
# if invoked without arguments, tells you what columns are present and
+ their indices, useful if there is a header row

use strict;

if (@ARGV) {
   while (<STDIN>) {
      my @fields=split(/\t/,$_);
      for (my $i=0; $i<=$#ARGV; $i++) {
         print $fields[$ARGV[$i]];
         print "\t" if $i<$#ARGV;
      print "\n";
} else {
   my $line;
   until ($line=~/\t/) { $line=<STDIN>; }
   chop $line;
   die "No lines to process" unless $line;
   my $i=0;
   for my $field (split(/\t/,$line)) {
      printf "%3d: $field\n",$i++;