JS noob
JS noob

Reputation: 487

BASH: split string on \n and store in array

I have the following string that I read in from a file in bash

BOB_ENV: DEV\nStorage: @MOM.KV(Name=lol-lol;SCT=c-s-string)\nConn__name: ab-cb-ac-one.sb.w.net\nTest: Test

I am trying to make the \n the delimiter and store into an array

I am not sure if I am doing it properly but I have the following script

test="BOB_ENV: DEV\nStorage: @MOM.KV(Name=lol-lol;SCT=c-s-string)\nConn__name: ab-cb-ac-one.sb.w.net\nTest: Test"
arr=(`echo $test`)
echo ${arr[1]}

right now it splits the string on the spaces I have in the string and stores into the array. I want to split on the \n in the string.

Upvotes: 2

Views: 1488

Answers (1)

anubhava
anubhava

Reputation: 784938

You can use printf '%b' to interpret \n as line break and read it into array using readarray:

s='BOB_ENV: DEV\nStorage: @MOM.KV(Name=lol-lol;SCT=c-s-string)\nConn__name: ab-cb-ac-one.sb.w.net\nTest: Test'

# read into array
readarray -t arr < <(printf '%b\n' "$s")

# check array content
declare -p arr

Output:

declare -a arr=([0]="BOB_ENV: DEV" [1]="Storage: @MOM.KV(Name=lol-lol;SCT=c-s-string)" [2]="Conn__name: ab-cb-ac-one.sb.w.net" [3]="Test: Test")

Upvotes: 2

Related Questions