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

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

    You can set the internal field separator (IFS) variable, and then let it parse into an array. When this happens in a command, then the assignment to IFS only takes place to that single command's environment (to read ). It then parses the input according to the IFS variable value into an array, which we can then iterate over.

    IFS=';' read -ra ADDR <<< "$IN"
    for i in "${ADDR[@]}"; do
        # process "$i"
    done
    

    It will parse one line of items separated by ;, pushing it into an array. Stuff for processing whole of $IN, each time one line of input separated by ;:

     while IFS=';' read -ra ADDR; do
          for i in "${ADDR[@]}"; do
              # process "$i"
          done
     done <<< "$IN"
    

提交回复
热议问题