【问题标题】:Bash conditionally split string into arrayBash 有条件地将字符串拆分为数组
【发布时间】:2016-10-06 18:58:19
【问题描述】:

我浏览了基于字符拆分输入的问题,但无法根据条件确定多个字符:

假设我有一个简单的 bash 脚本,它将以空格分隔的输入拆分为一个数组:

echo "Terms:"
read terms            // foo bar hello world
array=(${terms// / }) // ["foo", "bar", "hello", "world"]

我想要一个额外的条件,如果术语被另一个字符封装,则整个短语应该被拆分为一个。

例如用反勾号封装:

echo "Terms:"
read terms            // foo bar `hello world`
{conditional here}    // ["foo", "bar", "hello world"]

【问题讨论】:

  • foo bar `hello world`中没有不同的分隔符
  • @anubhava 感谢您的澄清。根据 bash,我没有得到关于什么是分隔符的任何具体定义,所以据我所知,我认为它与用于拆分输入的字符同义。我编辑了我的问题。
  • Backtick 用于 BASH 或 POSIX 中的命令替换。您可能可以使用单引号,例如foo bar 'hello world'
  • 有趣,很高兴知道。

标签: arrays bash split


【解决方案1】:

read的调用指定除空格以外的分隔符:

$ IFS=, read -a array   # foo,bar,hello world
$ printf '%s\n' "${array[@]}"
foo
bar
hello world

您可能应该将-r 选项与read 一起使用,但由于您不是,您可以让用户转义自己的空间:

$ read -a array    # foo bar hello\ world

【讨论】:

    【解决方案2】:

    您可以将您的输入传递给一个函数并使用$@ 来构建您的数组:

    makearr() { arr=( "$@" ); }
    
    makearr foo bar hello world
    # examine the array
    declare -p arr
    declare -a arr='([0]="foo" [1]="bar" [2]="hello" [3]="world")'
    
    # unset the array
    unset arr
    
    makearr foo bar 'hello world'
    # examine the array again
    declare -p arr
    declare -a arr='([0]="foo" [1]="bar" [2]="hello world")'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-26
      • 2021-10-09
      • 1970-01-01
      • 2018-05-01
      • 2016-01-27
      • 2015-08-28
      • 2023-02-24
      相关资源
      最近更新 更多