Search code examples
stringbash

Split a (multiline) string into array with a multichar delimiter


I have the following file and call cat myfile | ./myscript.sh:

(Item)
(Values)
blabla
blabla
(StopValues)
(Item)
(Values)
hello
hello
(StopValues)

In my script I save the piped content from cat to a variable: s=$(cat)

How can I split this string to have (in context of this example) an array containing 2 variables now, one saying

(Item)
(Values)
blabla
blabla
(StopValues)

the other one saying

(Item)
(Values)
hello
hello
(StopValues)

Solution

  • Assuming that the source string is in the variable s, the following bash script will populate the array variable a as required:

    a=()
    i=0
    while read -r line
    do
      a[i]="${a[i]}${line}"$'\n'
      if [ "$line" == "(StopValues)" ]
      then
        let ++i
      fi
    done <<< "$s"