[TriLUG] Changing the delimiter in bash - modify IFS env variable
jonc at nc.rr.com
jonc at nc.rr.com
Thu Aug 9 11:24:12 EDT 2007
I was writing a quick report using a bash script that handled names (with spaces in them) and thinking... "screw this, I should use python - at least then I could set my delimiter and then spaces won't screw me up!"
... and then the magic hit me, "Hay, I bet I can set my delimiter in bash. I'll bet its just some environment variable." And it is.
Bash uses IFS to tell it what acts as a separator when doing certain bash functions (most notably "for").
It defaults (on my boxen) to:
IFS=$'
'
That's: space, tab, and new-line.
Since I've got a list of names separated by commas (and containing spaces), I modified it to:
IFS=$',
'
And my for statements parce the names out just fine...
=== Bad parcing of names ===
#! /bin/bash
SALESREPS="Cob Ball,Moe Adnol,Faun Steamer"
for i in $SALESREPS; do
echo $i
done;
Cob
Ball,Moe
Adnol,Faun
Steamer
=== Good parcing of names ===
#! /bin/bash
IFS=$',
'
SALESREPS="Cob Ball,Moe Adnol,Faun Steamer"
for i in $SALESREPS; do
echo $i
done;
Cob Ball
Moe Adnol
Faun Steamer
===
And now, here is proof of my own stubborn stupidity...
http://www.trilug.org/pipermail/trilug/Week-of-Mon-20060522/042397.html
(which I read last year and then promptly deleted :-)
Thanks anyway, Chander Ganesan.
Jon
More information about the TriLUG
mailing list