#!/bin/sh
#
# Script to ease writing out columns from a text file
# RG 7 Oct. 2009
#
# protect against bad input
if [ $# -lt 2 ]
then 
    echo "Error: not enough arguments; use strip_columns.sh -h"
    exit 1
fi

# get options (help; start from line x) - leading : to ignore errors;trailing : since l has argument
line=0
while getopts ":hvl:" option
do
    case $option in
	"") 
	    ;;
	h)  echo " "
	    echo "usage : strip_columns.sh [-lvh] [line] file col1 [col2,...]"
	    echo "   -l : start extracting from line [line] counting from 1"
	    echo "   -h : print this help"
	    echo " "
	    exit 0
	    ;;
	l)  if [ $# -lt 4 ]
	    then 
	       echo "Error: not enough arguments; use strip_columns.sh -h"
	       exit 1
	    else
	       line=$OPTARG
	       shift
	       shift
	    fi
	    ;;
	\?) echo "Error: ilegal option --$0 (lh allowed)"
	    exit 1
	    ;;
    esac
done

# input file name
file=$1
shift

# build awk command to print list of columns
for i
do 
    list+="$"$i","
done
list=${list%","} # remove last ","
echo "{print $list}" > temporary_awk_program_file.awk

# read input file and write out columns
nrline=1
while read inline
do
    if [ $nrline -ge $line ] 
    then 
	echo $inline | awk -f temporary_awk_program_file.awk 
    fi
    (( nrline += 1 ))
done < $file

# write out stuff
echo "extracted columns $list from file $file starting at line $line"
echo "processed $nrline lines"
echo "done, bye"

# all done; cleanup and go
rm -f temporary_awk_program_file.awk

exit 0
