Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string with zsh as in Python

Tags:

string

split

zsh

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:

string="1::3"
a=(${(s/:/)string})
echo $a[1] # 1
echo $a[2] # 3 ?? I want an empty string, as in Python
like image 387
Olivier Verdier Avatar asked May 28 '10 15:05

Olivier Verdier


2 Answers

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

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:

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

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

like image 163
Olivier Verdier Avatar answered Nov 07 '22 15:11

Olivier Verdier


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

s="1::3"
saveIFS="$IFS"
IFS=':'
a=(${s})
IFS="$saveIFS"
like image 26
Dennis Williamson Avatar answered Nov 07 '22 15:11

Dennis Williamson