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

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

    Two bourne-ish alternatives where neither require bash arrays:

    Case 1: Keep it nice and simple: Use a NewLine as the Record-Separator... eg.

    IN="bla@some.com
    john@home.com"
    
    while read i; do
      # process "$i" ... eg.
        echo "[email:$i]"
    done <<< "$IN"
    

    Note: in this first case no sub-process is forked to assist with list manipulation.

    Idea: Maybe it is worth using NL extensively internally, and only converting to a different RS when generating the final result externally.

    Case 2: Using a ";" as a record separator... eg.

    NL="
    " IRS=";" ORS=";"
    
    conv_IRS() {
      exec tr "$1" "$NL"
    }
    
    conv_ORS() {
      exec tr "$NL" "$1"
    }
    
    IN="bla@some.com;john@home.com"
    IN="$(conv_IRS ";" <<< "$IN")"
    
    while read i; do
      # process "$i" ... eg.
        echo -n "[email:$i]$ORS"
    done <<< "$IN"
    

    In both cases a sub-list can be composed within the loop is persistent after the loop has completed. This is useful when manipulating lists in memory, instead storing lists in files. {p.s. keep calm and carry on B-) }

提交回复
热议问题