My previous question was flagged "duplicate" and I was pointed to this and this. The solutions provided on those threads does not solve this at all.
Content of file.txt:
Some line of text 0
Some line of text 1
Some line of text 2
PATTERN1
Some line of text 3
Some line of text 4
Some line of text 5
PATTERN2
Some line of text 6
Some line of text 7
Some line of text 8
PATTERN1
Some line of text 9
Some line of text 10
Some line of text 11
PATTERN2
Some line of text 12
Some line of text 13
Some line of text 14
I need to extract "PATTERN1" and "PATTERN2" + lines in between, and the following command does this perfectly:
awk '/PATTERN1 /,/PATTERN2/' ./file.txt
Output:
PATTERN1 Some line of text 3 Some line of text 4 Some line of text 5 PATTERN2 PATTERN1 Some line of text 9 Some line of text 10 Some line of text 11 PATTERN2
But now I am trying to create a bash script that:
- uses awk to find the lines between PATTERN1 and PATTERN2
- store each occurrence of PATTERN1 + lines in between + PATTERN2 in an array
- does 1 & 2 until the end of file.
To clarify. Means store the following lines inside the quotes:
"PATTERN1
Some line of text 3
Some line of text 4
Some line of text 5
PATTERN2"
to array[0]
and store the following lines inside the quotes:
"PATTERN1
Some line of text 9
Some line of text 10
Some line of text 11
PATTERN2"
to array[1]
and so on..... if there are more occurrence of PATTERN1 and PATTERN2
What I currently have:
#!/bin/bash
var0=`cat ./file.txt`
mapfile -t thearray < <(echo "$var0" | awk '/PATTERN1 /,/PATTERN2/')
The above does not work.
And as much as possible I do not want to use mapfile, because the script might be executed on a system that does not support it.
Based on this link provided:
myvar=$(cat ./file.txt)
myarray=($(echo "$var0" | awk '/PATTERN1 /,/PATTERN2/'))
But when I do echo ${myarray[1]}
I get a blank response.
And when I do echo ${myarray[0]}
I get:
PATTERN1 Some line of text 3 Some line of text 4 Some line of text 5 PATTERN2 PATTERN1 Some line of text 9 Some line of text 10 Some line of text 11 PATTERN2
What I expect when I do echo ${myarray[0]}
PATTERN1 Some line of text 3 Some line of text 4 Some line of text 5 PATTERN2
What I expect when I do echo ${myarray[1]}
PATTERN1 Some line of text 9 Some line of text 10 Some line of text 11 PATTERN2
Any help will be great.