Getting some commas into those spaces

by Carson Reynolds

Here is a troglodytic programming task I have brushed passed so often that I feel there ought to be a canned script to solve it. The problem is: you have a file with text separated by arbitrary whitespace and you want to covert it to a comma separated value (CSV) file. In short you need a space to CSV converter. By way of example, suppose you have:

field1 field2    field3
field4 field5 field6

But you really need to feed R, MATLAB, or Excel:

field1,field2,field3
field4,field5,field6

You have ten seconds, tell me in which language you’d solve that. My answer is “no language” … otherwise known as a BASH script wrapper for tr:

#!/bin/sh

# Converts the text file with fields seperated by whitespace named in
# the first argument into a CSV file for output named by the second
# argument.

# First test that two arguments were passed

ARGS=2        # Number of arguments expected.
E_BADARGS=65  # Exit value if incorrect number of args passed.

test $# -ne $ARGS && \
echo "Usage: `basename $0` $ARGS argument(s)" && \
echo "Example: `basename $0` inputfile outputfile" && \
exit $E_BADARGS

# Next convert whitespace to commas for CSV

tr -s '[:blank:]' ','  $2

Please download space-to-csv.sh, a small tool for a small problem.

Advertisements