2

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.

1
  • I want to split TEXT(variable with \n) into array in bash. Are you sure you want this? Are you asking XY question? Commented Jun 12, 2021 at 14:14

3 Answers 3

5

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")
Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

mapfile: -d: invavlid option
Depends on what linux distribution you are using. mapfile is a synonim for readarray, try with this one. I update the post...
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.