Korn Shell IFS When Declaring An Array

Korn Shell IFS When Declaring An Array

Post by absint » Tue, 08 Mar 2005 10:28:28



The standard Kornshell syntax for defining an array is
set -A arrayName elem1 elem2 elem3 elem4

Can I change the $IFS so I can pass in
set -A arrayName elem1,elem2,elem3,elem4

This is the code snippet:
I'm trying to do this in Kornshell using:

local oldIFS=$IFS
IFS=","
local newArray
set -A newArray `echo $1` [Which is one line from a CSV file]
IFS=$oldIFS

Currently the entire line is passed in as newArray[0].

I've also tried the following sed line:

Which I've bound to a splitFields function.

echo "${1}" | sed "s/^ */'/g;s/ *$/'/g;s/${2} */${2}/g;s/
*${2}/${2}/g;s/${2}/' '/g"

Which converts say "New York, Paris, London" to 'New York' 'Paris'
'London.'

But even if i pass this in as a parameter:
set -A newArray `splitFields "New York, Paris, London" ","`

Korn Shell ignores the quotes and reads the space so newArray[0]="New"
newArray[1]="York"

This won't work. Any suggestions?

 
 
 

Korn Shell IFS When Declaring An Array

Post by Chris F.A. Johnso » Tue, 08 Mar 2005 11:10:23



> The standard Kornshell syntax for defining an array is
> set -A arrayName elem1 elem2 elem3 elem4

> Can I change the $IFS so I can pass in
> set -A arrayName elem1,elem2,elem3,elem4

> This is the code snippet:
> I'm trying to do this in Kornshell using:

> local oldIFS=$IFS
> IFS=","
> local newArray
> set -A newArray `echo $1` [Which is one line from a CSV file]

   Why are you using echo?

set -A newArray $1

Quote:> IFS=$oldIFS

> Currently the entire line is passed in as newArray[0].

> I've also tried the following sed line:

> Which I've bound to a splitFields function.

> echo "${1}" | sed "s/^ */'/g;s/ *$/'/g;s/${2} */${2}/g;s/
> *${2}/${2}/g;s/${2}/' '/g"

> Which converts say "New York, Paris, London" to 'New York' 'Paris'
> 'London.'

> But even if i pass this in as a parameter:
> set -A newArray `splitFields "New York, Paris, London" ","`

> Korn Shell ignores the quotes and reads the space so newArray[0]="New"
> newArray[1]="York"

> This won't work. Any suggestions?

   What version of ksh are you using? If it's ksh93, you can use:

newArray=( $1 )

--
    Chris F.A. Johnson                  http://cfaj.freeshell.org/shell
    ===================================================================
    My code (if any) in this post is copyright 2005, Chris F.A. Johnson
    and may be copied under the terms of the GNU General Public License