#! /usr/bin/env bash

# Convert txt file $1 to csv.  Works on $1.txt if $1 not found.  With no $1, uses standard input.
# Assumes no spaces inside of fields; fields separated by one or more spaces.

# $var:t    ${var##*/}
# $var:h    ${var%/*}
# $var:e    ${var##*.}
# $var:r    ${var%.*}

inputfile=$1

if [[ "$1" != "" ]]; then
  if [[ ! -f $inputfile ]]; then inputfile=$inputfile.txt; fi
  if [[ ! -f $inputfile ]]; then echo
     "txt2csv: $inputfile not found"
     exit 2
  fi
fi
cat $inputfile | sed 's+  *+,+g' | sed 's+^,++' | sed 's+,$++'

