Both ZSH and Bash have some built-in string manipulations that can be useful at times.

Substrings

Given a test string:

word='hello - world - how - are - you'

Take elements (letters) 5 through 10

$word[5,10] == 'o - wo' # for zsh
${word:5:5} == '- wo'   # for bash

N.B.: in bash the first character is at index 0, in zsh this is at index 1!

Substring matching

To match a string with a substring, we can use:

  • ${str#substr} Deletes shortest match of $substr from front $str
  • ${str##substr} Deletes longest match of $substr from front $str

for example: take part before 'how*', or o*

${word%how*} == 'hello - world - '
${word%o*} == 'hello - world - how - are - y'
${word%%o*} == 'hell'

Or take the part after '* - '

${word#* - } = 'world - how - are - you'
${word##* - } = 'you'

Explode strings

To explode or split strings into array, we can use several zsh functions:

To split by ' - ', take 3rd element

${word[(ws: - :)3]} == 'how' # only zsh

Split by ' - ', take second element, capitalize

${(C)${word[(ws: - :)2]}} == 'World' # only zsh

Split by word, take first word

$word[(w)1] == 'hello' # only zsh

File rename examples

Get the file extension:

file=helloworld.multiple.dots.jpg
${file##*\.} == jpg
echo ${file##*\.}

Get the file base name:

file=helloworld.multiple.dots.jpg
${file%\.*} == helloworld.multiple.dots
echo ${file%\.*}

References