string 如何在bash中将包含字符“\n”的多行字符串拆分为字符串数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11746071/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to split a multi-line string containing the characters "\n" into an array of strings in bash?
提问by Cory Klein
I have a stringin the following format:
我有以下格式的字符串:
I'm\nNed\nNederlander
I'm\nLucky\nDay
I'm\nDusty\nBottoms
I would like to move this to an array of strings line by line such that:
我想将它逐行移动到一个字符串数组中,以便:
$ echo "${ARRAY[0]}"
I'm\nNed\nNederlander
$ echo "${ARRAY[1]}"
I'm\nLucky\nDay
$ echo "${ARRAY[2]}"
I'm\nDusty\nBottoms
However, I'm running into problems with the "\n" characters within the string itself. They are represented in the string as two separate characters, the backslash and the 'n', but when I try to do the array split they get interpreted as newlines. Thus typical string splitting with IFS
does not work.
但是,我遇到了字符串本身中“\n”字符的问题。它们在字符串中表示为两个单独的字符,反斜杠和“n”,但是当我尝试进行数组拆分时,它们被解释为换行符。因此,典型的字符串拆分IFS
不起作用。
For example:
例如:
$ read -a ARRAY <<< "$STRING"
$ echo "${#ARRAY[@]}" # print number of elements
2
$ echo "${ARRAY[0]}"
I'mnNednNederla
$ echo "${ARRAY[1]}"
der
回答by jordanm
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
.
默认情况下,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"
In order to do this in one-line (like you were attempting with read -a
), actually requires mapfile
in bash v4 or higher:
为了在一行中执行此操作(就像您尝试使用read -a
),实际上需要mapfile
在 bash v4 或更高版本中:
mapfile -t arr <<< "$string"
回答by chepner
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):
mapfile
更优雅,但可以在一个(丑陋的)行中执行此操作read
(如果您使用的 bash 版本早于 4,则很有用):
IFS=$'\n' read -d '' -r -a arr <<< "$string"