How do I split a string on a delimiter in Bash?

后端 未结 30 2019
萌比男神i
萌比男神i 2020-11-21 04:58

I have this string stored in a variable:

IN=\"bla@some.com;john@home.com\"

Now I would like to split the strings by ; delimite

30条回答
  •  被撕碎了的回忆
    2020-11-21 05:37

    Maybe not the most elegant solution, but works with * and spaces:

    IN="bla@so me.com;*;john@home.com"
    for i in `delims=${IN//[^;]}; seq 1 $((${#delims} + 1))`
    do
       echo "> [`echo $IN | cut -d';' -f$i`]"
    done
    

    Outputs

    > [bla@so me.com]
    > [*]
    > [john@home.com]
    

    Other example (delimiters at beginning and end):

    IN=";bla@so me.com;*;john@home.com;"
    > []
    > [bla@so me.com]
    > [*]
    > [john@home.com]
    > []
    

    Basically it removes every character other than ; making delims eg. ;;;. Then it does for loop from 1 to number-of-delimiters as counted by ${#delims}. The final step is to safely get the $ith part using cut.

提交回复
热议问题