如何将包含字符“\ n”的多行字符串拆分为bash中的字符串数组?

时间:2012-07-31 17:48:59

标签: arrays string bash escaping

我有一个字符串,格式如下:

I'm\nNed\nNederlander
I'm\nLucky\nDay
I'm\nDusty\nBottoms

我想将它逐行移动到一个字符串数组中,以便:

$ echo "${ARRAY[0]}"
I'm\nNed\nNederlander

$ echo "${ARRAY[1]}"
I'm\nLucky\nDay

$ echo "${ARRAY[2]}"
I'm\nDusty\nBottoms

但是,我遇到了字符串本身中“\ n”字符的问题。它们在字符串中表示为两个单独的字符,反斜杠和'n',但是当我尝试进行数组拆分时,它们会被解释为换行符。因此,IFS的典型字符串拆分不起作用。

例如:

$ read -a ARRAY <<< "$STRING"
$ echo "${#ARRAY[@]}"   # print number of elements
2

$ echo "${ARRAY[0]}"
I'mnNednNederla

$ echo "${ARRAY[1]}"
der

2 个答案:

答案 0 :(得分:27)

默认情况下,read内置允许\转义字符。要关闭此行为,请使用-r选项。通常情况下,您不会发现不想使用-r的情况。

string="I'm\nNed\nNederlander
I'm\nLucky\nDay
I'm\nDusty\nBottoms"

arr=()
while read -r line; do
   arr+=("$line")
done <<< "$string"

为了在一行中执行此操作(就像您尝试使用read -a一样),实际上在bash v4或更高版本中需要mapfile

mapfile -t arr <<< "$string"

答案 1 :(得分:12)

mapfile更优雅,但可以在read的一个(丑陋)行中执行此操作(如果您使用的是早于4的bash版本,则非常有用):

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