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

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

    The following Bash/zsh function splits its first argument on the delimiter given by the second argument:

    split() {
        local string="$1"
        local delimiter="$2"
        if [ -n "$string" ]; then
            local part
            while read -d "$delimiter" part; do
                echo $part
            done <<< "$string"
            echo $part
        fi
    }
    

    For instance, the command

    $ split 'a;b;c' ';'
    

    yields

    a
    b
    c
    

    This output may, for instance, be piped to other commands. Example:

    $ split 'a;b;c' ';' | cat -n
    1   a
    2   b
    3   c
    

    Compared to the other solutions given, this one has the following advantages:

    • IFS is not overriden: Due to dynamic scoping of even local variables, overriding IFS over a loop causes the new value to leak into function calls performed from within the loop.

    • Arrays are not used: Reading a string into an array using read requires the flag -a in Bash and -A in zsh.

    If desired, the function may be put into a script as follows:

    #!/usr/bin/env bash
    
    split() {
        # ...
    }
    
    split "$@"
    

提交回复
热议问题