1

In my use case I would like to change the value of IFS to a known separator (-). I tried the following:

OLDIFS=$IFS
IFS='-'
for x in $*
do
    echo $x
done
IFS=$OLDIFS

When using e.g. -a b -c d as input string I expect the output to be

a b
c d

However, what I get is

a
b
c
d

I'm on AIX.

Adrian Frühwirth
  • 42,970
  • 10
  • 60
  • 71
Aymanadou
  • 1,200
  • 1
  • 14
  • 36
  • 1
    Make sure you pass one argument to your shell script. `./foo "-a b -c d"` should produce the result you want – Brandin Apr 29 '14 at 10:52
  • 1
    Your expected result is wrong, this would return an empty line, followed by `a b ` followed by `c d`. If you remove the whitespaces from `IFS` they will not be used as separators resulting in an empty first token and a trailing space in the second token. – Adrian Frühwirth Apr 29 '14 at 11:14
  • Yes No problem for the empty line i just want to return an atomic token `a b` @AdrianFrühwirth – Aymanadou Apr 29 '14 at 11:17
  • 1
    @Aymanadou But `a b` != `a b `. – Adrian Frühwirth Apr 29 '14 at 11:25
  • Cannot reproduce your "observed" behaviour on AIX 6.1. – DevSolar Apr 29 '14 at 13:10
  • @AdrianFrühwirth actually in my usecase `a` is a parameter and `b` is the value of this parameter, so as a first step i want to tokenize my argument list to get parm|value in one token(no problem with trailing white spaces ...) in a second step i will split this token in parms and value – Aymanadou Apr 29 '14 at 13:24
  • @DevSolar i have the same version 6.1 and i always reproduce – Aymanadou Apr 29 '14 at 13:30
  • 1
    @Aymanadou Oh...please don't bake your own arguments parser, use [`getopts`](http://stackoverflow.com/a/16496491/612462) instead. – Adrian Frühwirth Apr 29 '14 at 13:35

2 Answers2

1

I tried your code and I get

a b
c d

Try this

$ cat >a <<.
#!/bin/sh
OLDIFS=$IFS
IFS='-'
for x in $*
do
    echo $x
done
IFS=$OLDIFS
.
$ chmod +x a
$ ./a "-a b -c d"

a b
c d
$
PeterMmm
  • 24,152
  • 13
  • 73
  • 111
1

Here is one way of getting this output using awk and avoid all the IFS manipulation:

s='-a b -c d'
echo "$s" | awk -F ' *- *' '{print $2 RS $3}'
a b
c d
anubhava
  • 761,203
  • 64
  • 569
  • 643