Bash by Example: String Replacement
Replace parts of a string using pattern matching syntax ${var/pattern/replacement} with this sample code.
Code
#!/bin/bash
filename="image.jpg"
# Replace first occurrence
# Syntax: ${var/pattern/replacement}
new_name=${filename/jpg/png}
echo "Convert: $filename -> $new_name"
text="apple banana apple orange"
# Replace ALL occurrences using double slash //
# Syntax: ${var//pattern/replacement}
clean_text=${text//apple/fruit}
echo "Original: $text"
echo "Cleaned: $clean_text"
# Delete substring (replace with empty)
no_spaces=${text// /}
echo "No spaces: $no_spaces"
# Replace prefix (#) or suffix (%)
file="backup.tar.gz"
echo "No ext: ${file%.tar.gz}"Explanation
Bash has powerful built-in string manipulation capabilities using parameter expansion. You can replace text within a variable without needing external tools like sed. This is faster and keeps your script self-contained.
The syntax ${variable/pattern/replacement} replaces the first match of pattern with replacement. To replace all matches, use a double slash: ${variable//pattern/replacement}.
If the replacement string is omitted (e.g., ${variable/pattern/}), the matched pattern is deleted from the string. This is useful for stripping whitespace or removing specific characters. You can also anchor patterns to the beginning (#) or end (%) of the string for more precise replacements.
Code Breakdown
$filename with "png".// indicates that every instance of "apple" should be replaced with "fruit".// ) with nothing (the part after the last slash is empty), effectively removing all spaces.${file%.tar.gz} removes the suffix ".tar.gz" from the end of the string. The % operator matches from the end.
