Results 1 to 2 of 2
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 = ...
- 12-21-2010 #1Just Joined!
- Join Date
- Aug 2009
- Posts
- 23
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
- 12-21-2010 #2
The environment variable IFS can be used to control the delimiter characters used by the shell to split input. So, for instance, you could do this:
Input will be split on any of the characters in IFS:Code:> IFS="," read var1 var2 var3 a,b,c > echo $var2 b
Also, you can more gracefully handle cases of different numbers of arguments being supplied on the input line if you read into an array:Code:> IFS=",; " read var1 var2 var3 var4 a, b c; d > echo $var2 b > echo $var4 d
Also, whitespace immediately around the field separator will be ignored, while whitespace in the middle of the field will be collapsed to a single space:Code:> IFS="," read -a vars a,b,c > echo ${#vars} 3 > echo ${vars[1]} b
If there's a comma at the end with no non-whitespace following it, the trailing text is not treated as a field:Code:> IFS="," read -a vars a , b c , d > echo ${vars[1]} b c
Code:> IFS="," read -a vars a,b,c,d, > echo ${#vars} 4 > echo ${vars[3]} d


Reply With Quote
