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

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

    Taken from Bash shell script split array:

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

    Explanation:

    This construction replaces all occurrences of ';' (the initial // means global replace) in the string IN with ' ' (a single space), then interprets the space-delimited string as an array (that's what the surrounding parentheses do).

    The syntax used inside of the curly braces to replace each ';' character with a ' ' character is called Parameter Expansion.

    There are some common gotchas:

    1. If the original string has spaces, you will need to use IFS:
      • IFS=':'; arrIN=($IN); unset IFS;
    2. If the original string has spaces and the delimiter is a new line, you can set IFS with:
      • IFS=$'\n'; arrIN=($IN); unset IFS;

提交回复
热议问题