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

后端 未结 30 1997
萌比男神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:43

    There are some cool answers here (errator esp.), but for something analogous to split in other languages -- which is what I took the original question to mean -- I settled on this:

    IN="bla@some.com;john@home.com"
    declare -a a="(${IN/;/ })";
    

    Now ${a[0]}, ${a[1]}, etc, are as you would expect. Use ${#a[*]} for number of terms. Or to iterate, of course:

    for i in ${a[*]}; do echo $i; done
    

    IMPORTANT NOTE:

    This works in cases where there are no spaces to worry about, which solved my problem, but may not solve yours. Go with the $IFS solution(s) in that case.

提交回复
热议问题