Thursday, February 3, 2022

[SOLVED] Bash. Split text to array by delimiter

Issue

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.


Solution

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")


Answered By - KamilCuk
Answer Checked By - Terry (WPSolving Volunteer)