Back to Blog

Zsh Tutorial #13: String Operations Every Developer Needs. #13

Sandy LaneSandy Lane

Video: Zsh Tutorial #13: String Operations Every Developer Needs. #13 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Zsh Tutorial #13: String Operations Every Developer Needs

Mastering string manipulation in Zsh is essential for efficient shell scripting. This guide covers fundamental operations such as measuring string length, extracting substrings, concatenation, search and replace patterns, case conversion, and splitting/joining strings using arrays.

Code

# String length
mystring="Hello, Zsh!"
echo "Length: ${#mystring}"  # Outputs: Length: 11

# Substring extraction (1-based indexing)
echo "Substring (1-5): ${mystring:0:5}"  # Outputs: Hello

# String concatenation
greeting="Hello"
name="World"
combined="${greeting}, ${name}!"
echo "$combined"  # Outputs: Hello, World!

# Check if string contains substring
if [[ $mystring == *"Zsh"* ]]; then
  echo "Contains 'Zsh'"
fi

# Empty/non-empty tests
empty=""
if [[ -z $empty ]]; then
  echo "String is empty"
fi
if [[ -n $mystring ]]; then
  echo "String is not empty"
fi

# Search and replace
text="I like apples and apples."
echo "${text/apples/oranges}"    # Replace first: I like oranges and apples.
echo "${text//apples/oranges}"   # Replace all: I like oranges and oranges.

# Strip prefix and suffix
file="archive.tar.gz"
echo "${file#*.}"   # Strip shortest prefix up to . : tar.gz
echo "${file##*.}"  # Strip longest prefix up to .  : gz
echo "${file%.*}"   # Strip shortest suffix from end: archive.tar
echo "${file%%.*}"  # Strip longest suffix from end : archive

# Case conversion
word="zsh scripting"
echo "${(U)word}"  # Uppercase: ZSH SCRIPTING
echo "${(L)word}"  # Lowercase: zsh scripting
echo "${(C)word}"  # Capitalize first letters: Zsh Scripting

# Case-insensitive comparison
str1="Apple"
str2="apple"
if [[ "${str1:l}" == "${str2:l}" ]]; then
  echo "Strings are equal ignoring case"
fi

# Split string into array
csv="red,green,blue"
colors=("${(s:, :)csv}")
for color in "${colors[@]}"; do
  echo "Color: $color"
done

# Join array into string
joined="${(j:|:)colors}"
echo "Joined with '|': $joined"  # Outputs: red|green|blue

Key Points

  • Use ${#var} to get string length and ${var:start:length} for substrings with zero-based indexing.
  • Search and replace supports single (${var/old/new}) and global (${var//old/new}) substitutions.
  • Prefix and suffix removal use #/## and %/%% operators for shortest and longest matches.
  • Case conversion flags ${(U)}, ${(L)}, and ${(C)} transform strings to uppercase, lowercase, and capitalized forms.
  • Split strings into arrays with ${(s:delim:)var} and join arrays with ${(j:delim:)array} for flexible string handling.