LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Reading comma separated variable into other variables in shell script (https://www.linuxquestions.org/questions/programming-9/reading-comma-separated-variable-into-other-variables-in-shell-script-851645/)

suryaemlinux 12-21-2010 02:28 PM

Reading comma separated variable into other variables in shell script
 
Hi,
In shell script, I have a variable var = xyz, inn, day, night, calif ....n and I would like to read them in to var1 = xzy, var2 = inn, var3= day, var4 = night....var[n].
probably in a loop. I would like to read the variables until end of the line. Comma is the delimiter and there's no comma at the end.

For example:

var = inn, day, grocery

I would like to read it like

var1 = inn, var2 = day, var3 = grocery

Another case:
var = day, grocery, store, road, highway

I would like to read it as

var1 = day, var2 = grocery, var3 = store, var4 = road, var5 = highway

Snark1994 12-21-2010 04:16 PM

Code:

list=(`echo $var | tr ',' ' '`)
should work, I think. It uses 'tr' to replace the commans with spaces and builds that into a list :)

grail 12-21-2010 11:45 PM

Or you can use simple substitution:
Code:

arr=( ${var//,/ } )

theNbomr 12-22-2010 09:58 AM

It should be noted that the solutions that have been posted are probably the closest solution to the original question that can be reached. The OP asked for a way to magically create a series of scalar variables with ascending numeric suffixes. This is probably impossible, however the solutions given by Snark1994 and grail create a single array variable, which should be a close enough (probably superior) approximation.
Not given in either of the solutions was a method to access individual elements of the array variable (and which some of us find non-obvious) :
Code:

# re: grail's method

echo ${arr[1]}

--- rod.

PTrenholme 12-22-2010 12:37 PM

Code:

#!/bin/bash
var="inn, day, grocery"
IFS=" ,"
i=0
for val in ${var}
do
  i=$((++i))
  eval var${i}="${val}"
done
for ((j=1;j<=i;++j))
do
  name="var${j}"
  echo ${name}=${!name}
done

Output:
Code:

$ ./suryaemlinux
var1=inn
var2=day
var3=grocery


grail 12-22-2010 07:38 PM

Thanx rod ... sometimes forget what seems like the obvious part :)


All times are GMT -5. The time now is 10:54 AM.