How to split a multi-line string containing the characters "\n" into an array of strings in bash? [duplicate] How to split a multi-line string containing the characters "\n" into an array of strings in bash? [duplicate] arrays arrays

How to split a multi-line string containing the characters "\n" into an array of strings in bash? [duplicate]


By default, the read builtin allows \ to escape characters. To turn off this behavior, use the -r option. It is not often you will find a case where you do not want to use -r.

string="I'm\nNed\nNederlanderI'm\nLucky\nDayI'm\nDusty\nBottoms"arr=()while read -r line; do   arr+=("$line")done <<< "$string"

In order to do this in one-line (like you were attempting with read -a), actually requires mapfile in bash v4 or higher:

mapfile -t arr <<< "$string"


mapfile is more elegant, but it is possible to do this in one (ugly) line with read (useful if you're using a version of bash older than 4):

IFS=$'\n' read -d '' -r -a arr <<< "$string"