Find the answer to your Linux question:
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 = ...
  1. #1
    Just 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

  2. #2
    Linux Newbie tetsujin's Avatar
    Join Date
    Oct 2008
    Posts
    115
    Quote Originally Posted by suryaemlinux View Post
    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.
    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:

    Code:
    > IFS="," read var1 var2 var3
    a,b,c
    > echo $var2
    b
    Input will be split on any of the characters in IFS:
    Code:
    > IFS=",; " read var1 var2 var3 var4
    a, b c; d
    > echo $var2
    b
    > echo $var4
    d
    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 -a vars
    a,b,c
    > echo ${#vars}
    3
    > echo ${vars[1]}
    b
    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    ,   d   
    > echo ${vars[1]}
    b c
    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}
    4
    > echo ${vars[3]}
    d

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...