string 按换行符拆分bash字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19771965/
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
Split bash string by newline characters
提问by sites
I found this.
我找到了这个。
And I am trying this:
我正在尝试这个:
x='some
thing'
y=(${x//\n/})
And I had no luck, I thought it could work with double backslash:
我没有运气,我认为它可以使用双反斜杠:
y=(${x//\n/})
But it did not.
但它没有。
To test I am not getting what I want I am doing:
为了测试我没有得到我想要的我正在做的事情:
echo ${y[1]}
Getting:
获得:
some
thing
Which I want to be:
我想成为:
some
I want y
to be an array [some, thing]
. How can I do this?
我想y
成为一个数组[some, thing]
。我怎样才能做到这一点?
回答by Sir Athos
Another way:
其它的办法:
x=$'Some\nstring'
readarray -t y <<<"$x"
Or, if you don't have bash 4, the bash 3.2 equivalent:
或者,如果您没有 bash 4,则 bash 3.2 相当于:
IFS=$'\n' read -rd '' -a y <<<"$x"
You can also do it the way you were initially trying to use:
您也可以按照最初尝试使用的方式进行操作:
y=(${x//$'\n'/ })
This, however, will not function correctly if your string already contains spaces, such as 'line 1\nline 2'
. To make it work, you need to restrict the word separator before parsing it:
但是,如果您的字符串已经包含空格,例如'line 1\nline 2'
. 要使其工作,您需要在解析之前限制单词分隔符:
IFS=$'\n' y=(${x//$'\n'/ })
...and then, since you are changing the separator, you don't need to convert the \n
to space
anymore, so you can simplify it to:
...然后,由于您正在更改分隔符,您不再需要将 转换\n
为space
,因此您可以将其简化为:
IFS=$'\n' y=($x)
This approach will function unless$x
contains a matching globbing pattern (such as "*
") - in which case it will be replaced by the matched file name(s). The read
/readarray
methods require newer bash versions, but work in all cases.
除非$x
包含匹配的通配符模式(例如“ *
”),否则此方法将起作用- 在这种情况下,它将被匹配的文件名替换。该read
/readarray
方法需要新的bash版本,但工作在所有情况下。
回答by Fleshgrinder
There is another way if all you want is the text up to the first line feed:
如果你想要的只是第一个换行的文本,还有另一种方法:
x='some
thing'
y=${x%$'\n'*}
After that y
will contain some
and nothing else (no line feed).
之后y
将包含some
而没有其他内容(没有换行符)。
What is happening here?
这里发生了什么?
We perform a parameter expansion substring removal(${PARAMETER%PATTERN}
) for the shortest match up to the first ANSI C line feed($'\n'
) and drop everything that follows (*
).
我们对第一个ANSI C 换行符( ) 之前的最短匹配执行参数扩展子字符串删除( ) 并删除( ) 之后的所有内容。${PARAMETER%PATTERN}
$'\n'
*