【问题标题】:IFS equal to newline character is not working in bashIFS 等于换行符在 bash 中不起作用
【发布时间】: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'。

标签: bash ifs


【解决方案1】:

您尝试的主要问题是 分词 没有使用 herestring。来自 man bash:

Here Strings
   A variant of here documents, the format is:

          <<<word

   ... Pathname expansion and word splitting are not performed.
   The result is supplied as a single string to the command on its 
   standard input.

Bash 确实提供了一个 heredoc(例如 man bash 中的“Here Document”),word-splitting 将使用默认的 IFS 执行。然而,即便如此,您仍然会将文字 '\n' 作为数组内容的一部分读取。不用担心,bash 提供了一种特定方式,可以通过 -t 选项到 readarray(a/k/a mapfile)来避免这种情况。

一个尽可能接近您最初尝试的简短示例是:

readarray -t arr << EOF
line1
line2
line3
EOF
declare -p arr

这会导致您的行按需要保存,例如输出将是:

declare -a arr='([0]="line1" [1]="line2" [2]="line3")'

另一种选择是使用进程替换并让printf提供拆分,例如

readarray -t arr < <(printf "line1\nline2\nline3\n")

在不包含换行符的情况下填充数组的关键是readarray -t,允许发生分词的关键是避免herestring。

【讨论】:

    【解决方案2】:

    来自 bash 手册,bash 内置部分:

    阅读

    read [-ers] [-a aname] [-d delim] [-i text] [-n nchars]
        [-N nchars] [-p prompt] [-t timeout] [-u fd] [name …]
    
    One line is read from the standard input, or from the file descriptor fd supplied as an argument to the -u option, 
    

    行分隔符可以用-d指定

    -d 分隔符

    The first character of delim is used to terminate the input line, rather than newline.
    

    注意,后面跟一个空参数-d '',行分隔符将是nul字符,如果输入中没有nul字符,它可以用来读取整个输入。

    但是即使使用-r 模式,读取速度也很慢。

    对于较大的输入,更快的解决方案是使用分词:

    input=$'line1\nline2\nline3'
    IFS=$'\n';set -f;arr=($input);set +f;IFS=$' \t\n'
    

    注意set -f 以避免全局匹配阶段。

    【讨论】:

      猜你喜欢
      • 2021-12-29
      • 2013-10-12
      • 2016-10-02
      • 2017-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-09
      • 1970-01-01
      相关资源
      最近更新 更多