Loop through a comma-separated shell variable

前端 未结 8 1896
醉话见心
醉话见心 2020-12-22 18:15

Suppose I have a Unix shell variable as below

variable=abc,def,ghij

I want to extract all the values (abc, def an

相关标签:
8条回答
  • 2020-12-22 19:08

    If you set a different field separator, you can directly use a for loop:

    IFS=","
    for v in $variable
    do
       # things with "$v" ...
    done
    

    You can also store the values in an array and then loop through it as indicated in How do I split a string on a delimiter in Bash?:

    IFS=, read -ra values <<< "$variable"
    for v in "${values[@]}"
    do
       # things with "$v"
    done
    

    Test

    $ variable="abc,def,ghij"
    $ IFS=","
    $ for v in $variable
    > do
    > echo "var is $v"
    > done
    var is abc
    var is def
    var is ghij
    

    You can find a broader approach in this solution to How to iterate through a comma-separated list and execute a command for each entry.

    Examples on the second approach:

    $ IFS=, read -ra vals <<< "abc,def,ghij"
    $ printf "%s\n" "${vals[@]}"
    abc
    def
    ghij
    $ for v in "${vals[@]}"; do echo "$v --"; done
    abc --
    def --
    ghij --
    
    0 讨论(0)
  • 2020-12-22 19:08
    #/bin/bash   
    TESTSTR="abc,def,ghij"
    
    for i in $(echo $TESTSTR | tr ',' '\n')
    do
    echo $i
    done
    

    I prefer to use tr instead of sed, becouse sed have problems with special chars like \r \n in some cases.

    other solution is to set IFS to certain separator

    0 讨论(0)
提交回复
热议问题