Skip to content

Instantly share code, notes, and snippets.

@mattmc3
Last active March 31, 2024 15:34
Show Gist options
  • Save mattmc3/76ad634f362b5a9a54f1779a4737d5ae to your computer and use it in GitHub Desktop.
Save mattmc3/76ad634f362b5a9a54f1779a4737d5ae to your computer and use it in GitHub Desktop.
ZSH - split string into array

Example splitting string on slash character in ZSH.

$ str=part1/part2/part3
$ parts=(${(@s:/:)str})
$ echo $parts
part1 part2 part3
$ echo ${#parts[@]}
3

You can use split ${(@s:/:)str} and indexing [start,end] to do more sophisticated surgery on string parts. If you need to reassemble, simply join back on the same separator ${(@j:/:)str}.

$ url="https://github.com/sorin-ionescu/prezto/blob/master/modules/history/init.zsh"
$ repo="${(@j:/:)${(@s:/:)url}[4,5]}"
$ echo $repo
sorin-ionescu/prezto

An example from the Zsh docs which shows splitting:

$ foo=(ax1 bx1)
$ print -l -- ${(s/x/)foo}
a
1 b
1

Getting the first 2 parts

$ str=a/b/c/d/e/f
$ parts=(${(@s:/:)str})
$ echo ${(@j:/:)parts[1,2]}
a/b

Parameter expansion: see docs

$ str=part1/part2/part3
$ echo ${str%%/*}
part1
$ echo ${str%/*}
part1/part2
$ echo ${${str%/*}#*/}
part2
$ echo ${str#*/}
part2/part3
$ echo ${str##*/}
part3

Word splitting is done with the '=' character:

$ sentence="ls -l -A -h"
$ arr=(${=sentence})
$ print -l -- $arr
ls
-l
-A
-h
@j13ag0
Copy link

j13ag0 commented Feb 12, 2023

Very useful. Thanks -jg-

@YetAnotherAlexWithBadMemory

Thank! You've saved my 2-3 days!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment