1

Can somebody help me out. I want to split TEXT(variable with \n) into array in bash.

Ok, I have some text-variable:

variable='13423exa*lkco3nr*sw
kjenve*kejnv'

I want to split it in array. If variable did not have new line in it, I will do it by:

IFS='*' read -a array <<< "$variable"

I assumed the third element should be:

echo "${array[2]}"
>sw
>kjenve

But with new line it is not working. Please give me right direction.

Antonio Petricca
  • 8,891
  • 5
  • 36
  • 74
  • `I want to split TEXT(variable with \n) into array in bash.` Are you sure you want this? Are you asking XY question? – KamilCuk Jun 12 '21 at 14:14

3 Answers3

4

Use readarray.

$ variable='13423exa*lkco3nr*sw
kjenve*kejnv'
$ readarray -d '*' -t arr < <(printf "%s" "$variable")
$ declare -p arr
declare -a arr=([0]="13423exa" [1]="lkco3nr" [2]=$'sw\nkjenve' [3]="kejnv")

mapfile: -d: invavlid option

Update bash, then use readarray.

If not, replace separator with zero byte and read it element by element with read -d ''.

arr=()
while IFS= read -d '' -r e || [[ -n "$e" ]]; do
     arr+=("$e")
done < <(printf "%s" "$variable" | tr '*' '\0');
declare -p arr
declare -a arr=([0]="13423exa" [1]="lkco3nr" [2]=$'sw\nkjenve' [3]="kejnv")
KamilCuk
  • 120,984
  • 8
  • 59
  • 111
1

You can use the readarray command and use it like in the following example:

readarray -d ':' -t my_array <<< "a:b:c:d:"

for (( i = 0; i < ${#my_array[*]}; i++ )); do  
  echo "${my_array[i]}"  
done  

Where the -d parameter defines the delimiter and -t ask to remove last delimiter.

Antonio Petricca
  • 8,891
  • 5
  • 36
  • 74
0

Use a ending character different than new line

end=.
read -a array -d "$end" <<< "$v$end"

Of course this solution suppose there is at least one charecter not used in your input variable.

Dri372
  • 1,275
  • 3
  • 13