#!/bin/bash

#extract columns from TNS tsv files
#ex_TNS -c col1,..,coln {-s} {-h}  TNS1.tsv TNS2.tsv... | pipe
#output: columns col1,.., coln
# -c list of column numbers, comma separated, no space in between
# -s show header columns
#
# [] default, {} optional, all others required
#-----------------------------------------------------------------------
HELP=; SHOW=;
#-----------------------------------------------------------------------

while getopts c:sh OPTVAL
do 
    case $OPTVAL in
	c) reqcol=$OPTARG;;
	s) SHOW=1;;
	h) HELP=1;;
	*) echo "ex_TNS -h for help"; exit -1;;
    esac
done
shift $((OPTIND-1))

if [ $HELP ]; then
    echo "ex_TNS -c col1,..,coln {-s}  TNS1.tsv TNS2.. | pipe"
    echo "-c list of column numbers, comma separated, no space"
    echo "-s show header columns"
    exit
fi
[ -z $reqcol ] && { echo "must specify columns; exiting"; exit -1;}

#-----------------------------------------------------------------------
# check to see if data is being supplied by pipe
#-----------------------------------------------------------------------
if [ $# -eq 0 ]; then
   if [ -p /dev/stdin ]; then
	set -- "/dev/stdin"			#set $1=/dev/stdin
   else
	echo "no file given nor is there a trailing pipe"; exit -1
   fi
fi

for i in $*
do
  if [ $SHOW ]; then
    sed 's/"//g' $i | cut -f$reqcol 
  else
    sed '1d;s/"//g' $i | cut -f$reqcol 
  fi
done 
