【发布时间】:2018-12-03 05:48:21
【问题描述】:
我有一个多行字符串,我想根据\n 进行拆分,为此我设置了IFS=$'\n',但它不起作用,我也尝试过IFS= 和IFS="
",但没有运气。
下面是示例代码
IFS=$'\n' read -ra arr <<< "line1\nline2\nline3"
printf "%s\n" "${arr[@]}"
# it only generates array of length 1
我正在使用 Ubuntu 和 bash 版本
GNU bash, version 4.4.19(1)-release (x86_64-pc-linux-gnu)
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later
<http://gnu.org/licenses/gpl.html>
This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
有人能指出显而易见的吗?
【问题讨论】:
-
如果命令成功,
printf将产生相同的结果。你究竟是如何确定数组的大小的? -
您提供了一个带引号的字符串,例如
'line1\nline2\nline3',不会出现分词。 -
@tripleee by
echo ${#arr[@]}导致1。 -
@DavidC.Rankin ,编辑问题仍然是相同的结果,没有得到拆分。
-
问题是您实际上并没有读取输入,您提供的是一个字符串,无论是单引号还是双引号,都不会发生分词。您的默认
IFS是" \t\n"(space tab newline),因此无需更改IFS。这是关于 shell 如何处理文字的怪癖之一。此外,您只阅读一次。您似乎想使用readarray或mapfile而不是read -a。您可能还会将-a与-a -d '\n'混淆,您要指定分隔符是'\n'。