#!/bin/bash

# ipac2csv  file1.tbl file2.tbl ... -> file1.csv file2.csv .. 
# converts IPAC Table file into csv files
# file.csv has only data lines with FS=";"
# all modern tools (awk, csvkit, sort, etc) can be applied to csv files

# nota bene: for some reason the use of FS="|" seems to be problematic
# so using ";" instad

[ $# -eq 0 ] && {echo 'converts  IPAC tbl files to csv files with FS="|"';exit;}

for IFILE; do

 OFILE=${IFILE%.*}".csv"

 PIPES=$(sed -n '/|/{p;q;}' $IFILE | gsed 's/./&\n/g'| nl | sed -n 's/|//p' | xargs)

 awk -v PIPES="$PIPES" 'BEGIN{split(PIPES,ind)}   
     /^ /{b="";n=split($0,a,""); for (i in ind){a[ind[i]]=";"}      
     delete a[1]; delete a[n]; for (i in a){b=b a[i]}; print b}' \
     $IFILE > $OFILE
done