views:

126

answers:

2

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?

The following attempt fails:

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

Never mind, here is the solution:

a=("${(s/:/)s}") # notice the quotes

echo $a[1] # 1, good
echo $a[2] # nothing, good
echo $a[3] # 3, good

Edit

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:

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

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

Olivier
A: 

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

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