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

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

    In Bash, a bullet proof way, that will work even if your variable contains newlines:

    IFS=';' read -d '' -ra array < <(printf '%s;\0' "$in")
    

    Look:

    $ in=$'one;two three;*;there is\na newline\nin this field'
    $ IFS=';' read -d '' -ra array < <(printf '%s;\0' "$in")
    $ declare -p array
    declare -a array='([0]="one" [1]="two three" [2]="*" [3]="there is
    a newline
    in this field")'
    

    The trick for this to work is to use the -d option of read (delimiter) with an empty delimiter, so that read is forced to read everything it's fed. And we feed read with exactly the content of the variable in, with no trailing newline thanks to printf. Note that's we're also putting the delimiter in printf to ensure that the string passed to read has a trailing delimiter. Without it, read would trim potential trailing empty fields:

    $ in='one;two;three;'    # there's an empty field
    $ IFS=';' read -d '' -ra array < <(printf '%s;\0' "$in")
    $ declare -p array
    declare -a array='([0]="one" [1]="two" [2]="three" [3]="")'
    

    the trailing empty field is preserved.


    Update for Bash≥4.4

    Since Bash 4.4, the builtin mapfile (aka readarray) supports the -d option to specify a delimiter. Hence another canonical way is:

    mapfile -d ';' -t array < <(printf '%s;' "$in")
    

提交回复
热议问题