1

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)
2
  • Not an exact duplicate, since you are not mentioning anything about arrays, but the answers on this question of mine may give you some ideas: stackoverflow.com/questions/14630940/… Commented Feb 28, 2017 at 9:35
  • @user000001 besides a general confusion what I see there is that inside his string he always has characters he wants to have removed (which can be used as delimiter, e.g. '======= ' or '/') I do not have anything that should be removed from my string Commented Feb 28, 2017 at 9:45

1 Answer 1

2

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"
Sign up to request clarification or add additional context in comments.

7 Comments

one element of the array then contains only one line, e.g. "blabla", I'd rather want the "whole part" in one element just as described in the question
@RandomDisplayName Did you try running the code or you judge it without running?
I tried it, there's a twist though that might cause this to happen, I have the content in a file and pipe it to my script, I updated my question
Nevermind, it was my fault, when I echo my array like echo ${a[0]} its perfectly fine, but when I iterate through it with a for each loop, the item is always just one word\n is there a way I can get the full output just like when echoing ${a[0]}?
@RandomDisplayName You must quote your variable expansions: for x in "${a[@]}"; do ... done
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.