[NTLUG:Discuss] A quick script anyone?

Daniel Hauck daniel at yacg.com
Thu Jul 31 13:26:07 CDT 2008


Eric Schnoebelen さんは書きました:
> Daniel Hauck writes:
> - Parsing a CSV file and generating some output.
> - 
> - I have a list where the first field is a number and the next two are
> - text fields.  A line would look like this:
> - 
> - 10, "US", "United States of America"
> - 
> - I just need to be able to parse this line to fill some variables.  The
> - output part I have down pretty well and will be able to transform this
> - file (once I get the line parsing part down) into the output desired.
> 
> Here's a start for you..  You're still going to have quotes
> around the strings, but that may be useful for later evaluation
> of the strings.
> 
> 	#!/bin/sh
> 	#
> 	OIFS="${IFS}"
> 	IFS="${IFS},"  
> 	while read num short long; do
> 	    echo ${num}:${short}:${long}
> 	done
> 	IFS="${OIFS}"
> 
> The "trick" is changing the Input Field Seperator string to
> include the comma. Doing that, the shell naturally splits on the
> comma, as well as other white space.  By adding it to the
> standard IFS (which is [\t\ \n]), the white space and comma are
> gobbled and used as seperators between words.
> 

There are probably better ways, but here's what I did:

#!/bin/sh
OIFS="${IFS}"
IFS="${IFS},"
while read num short long; do
  sarank=${num}
  sasuffix=${short:1:2}
  sadescrl=${#long}
  sadescrd=`expr $sadescrl - 2`
  sadescrp=${long:1:sadescrd}

  echo "header RELAY_$sasuffix X-Relay-Countries=~/\b$sasuffix\b/"
  echo "describe RELAY_$sasuffix      Relayed through $sadescrp"
  echo "score RELAY_$sasuffix $sarank"
  echo ""
done
IFS="${OIFS}"

The output is exactly what I wanted.  The "sasuffix" part takes
advantage of the expectation that there are only two characters I care
about in this field.  I could have duplicated the following calculated
activity for consistency, but decided against it.

If there are better ways, I'm interested in learning them.  This is just
the results of informal/random searching and pre-existing knowledge.



More information about the Discuss mailing list