string 像在 Python 中一样使用 zsh 拆分字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2930238/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 00:45:57  来源:igfitidea点击:

Split string with zsh as in Python

stringsplitzsh

提问by Olivier Verdier

In python:

在蟒蛇中:

s = '1::3'
a = s.split(':')
print a[0] # '1' good
print a[1] # '' good
print a[2] # '3' good

How can I achieve the same effect with zsh?

我怎样才能达到同样的效果zsh

The following attempt fails:

以下尝试失败:

string="1::3"
a=(${(s/:/)string})
echo $a[1] # 1
echo $a[2] # 3 ?? I want an empty string, as in Python

回答by Olivier Verdier

The solution is to use the @modifier, as indicated in the zsh docs:

解决方案是使用@修饰符,如zsh 文档中所示

string="1::3"
a=("${(@s/:/)string}") # @ modifier

By the way, if one has the choice of the delimiter, it's much easier and less error prone to use a newline as a delimiter. The right way to split the lines with zsh is then:

顺便说一句,如果可以选择分隔符,那么使用换行符作为分隔符会更容易且更不容易出错。使用 zsh 拆分行的正确方法是:

a=("${(f)string}")

I don't know whether or not the quotes are necessary here as well...

我不知道这里是否也需要引号......

回答by Paused until further notice.

This will work in both zsh (with setopt shwordsplitor zsh -y) and Bash (zero-based arrays):

这将适用于 zsh(带setopt shwordsplitzsh -y)和 Bash(从零开始的数组):

s="1::3"
saveIFS="$IFS"
IFS=':'
a=(${s})
IFS="$saveIFS"