Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash splitting a multi line string by a multi-character delimiter into an array

Tags:

bash

shell

awk

I have searched for a similar topic here but most questions included single-character delimiter.

I have this sample of text:

Some text here,
continuing on next lineDELIMITERSecond chunk of text
which may as well continue on next lineDELIMITERFinal chunk

And the desired output is a list (extracted=()) which contains:

  1. Some text here, continuing on next line
  2. Second chunk of text which may as well continue on next line
  3. Final chunk

As could be seen from the sample, "DELIMITER" is used as a splitting delimiter.

I have tried numerous samples on SO incl awk, replacing etc.

like image 886
Hubbs Avatar asked Feb 11 '26 20:02

Hubbs


2 Answers

In case you don't want to change default RS value then could you please try following.

awk '{gsub("DELIMITER",ORS)} 1' Input_file
like image 60
RavinderSingh13 Avatar answered Feb 13 '26 14:02

RavinderSingh13


With AWK please try the following:

awk -v RS='^$' -v FS='DELIMITER' '{
    n = split($0, extracted)
    for (i=1; i<=n; i++) {
        print i". "extracted[i]
    }
}' sample.txt

which yields:

1. Some text here,
continuing on next line
2. Second chunk of text
which may as well continue on next line
3. Final chunk

If you require to transfer the awk array to bash array, further step will be needed depending on the succeeding process on the array.

like image 40
tshiono Avatar answered Feb 13 '26 15:02

tshiono