ZSH中有没有办法将字符串分割成一个数组,并用空格(“”)分隔值?

问题描述 投票:0回答:2

我有这个代码:

carp="2 hello 192.180.00.00"
array=( ${carp} )
echo "\n${array[2]}"

我正在尝试将 carp 分成一个名为 array 的数组。我的输出应该是“hello”,但它只是打印空白。有没有简单的方法将鲤鱼拆分成数组?

zsh variable-assignment
2个回答
2
投票

zsh 有一个参数扩展语法:

${=spec}
。要修改您的示例,它将是:

carp="2 hello 192.180.00.00"
array=( ${=carp} )
echo "\n${array[2]}"

描述是:

在spec评估过程中使用SH_WORD_SPLIT的规则进行分词,但无论参数是否出现在双引号中;如果“=”加倍,则将其关闭。这会强制参数扩展在替换之前被分割成单独的单词,并使用 IFS 作为分隔符。在大多数其他 shell 中,这是默认完成的。


0
投票

可以使用参数标志

z
:

  z      Split the result of the expansion into words using shell parsing to find the words, 
         i.e. taking into account any quoting in the value.  Comments are not treated
         specially but as ordinary strings, similar to interactive shells with the
         INTERACTIVE_COMMENTS option unset (however, see the Z flag below for related options)
carp="2 hello 192.180.00.00"
array=( ${(z)carp} )
echo "\n${array[2]}"

或者通过使用

s
指定自定义分割:

   s:string:
          Force field splitting at the separator string.  Note that a string of two or more characters means that all of them must match in sequence; this differs from the treatment of two or more
          characters in the IFS parameter.  See also the = flag and the SH_WORD_SPLIT option.  An empty string may also be given in which case every character will be a separate element.

          For historical reasons, the usual behaviour that empty array elements are retained inside double quotes is disabled for arrays generated by splitting; hence the following:

                line="one::three"
                print -l "${(s.:.)line}"

          produces two lines of output for one and three and elides the empty field.  To override this behaviour, supply the ‘(@)' flag as well, i.e.  "${(@s.:.)line}".
carp="2 hello 192.180.00.00"
array=( ${(s/ /)carp} )
echo "\n${array[2]}"

您还可以像这样省去创建另一个变量:

carp="2 hello 192.180.00.00"
echo "\n${${(z)carp}[2]}"
© www.soinside.com 2019 - 2024. All rights reserved.