Dup Ver Goto 📝

Zsh Variable Substitution

To
41 lines, 143 words, 967 chars Page 'Substitution1' does not exist.

Substrings

Zsh uses the $var[a,b] syntax where it extracts the substring from a to b inclusive (b is position, not length like with substr()). Use -1 for the end of the string. Indexing is 1-based, so $var[1] is the first character of $var if $var is not an array, else it is the first element of the array.

% name="John"
% echo $name[1,2]

Changing case to upper or lower

Sources: official docs and scriptingosx.com For zsh

% name="John Doe"
% echo ${name:l}
john doe
% echo ${name:u}
JOHN DOE

# Capitalise first letter, rest lowercase
% name="jOHN"
% echo "${name[0,1]:u}${name[2,-1]:l}"
John

Arrays

% a=(hello world mr flibble)
% echo $a[1]
hello
% echo $a[3]
mr
% echo $a[3,4]
mr flibble
% echo $a[-1,-1]
flibble
% echo $a[-2,-1]
mr flibble
% echo $a[-1,-2]
# blank