String Replacement
String replacement is like using find-and-replace on a story: swap the first matching word, or swap every single one of them if you use the double-slash way.
In this page:
Syntax
${variable/pattern/replacement} # first match
${variable//pattern/replacement} # all matches
String Replacement
${variable/pattern/replacement} replaces the first match of pattern in the string, while ${variable//pattern/replacement} replaces every match.
This is a built-in alternative to piping through sed for simple substitutions. Patterns support basic globbing, not full regular expressions.
Note:
Use the double-slash form,
${var//old/new}, when you need to replace all occurrences, not just the first.Example: String Replacement
#!/bin/bash
text="foo bar foo baz"
echo "${text/foo/qux}"
echo "${text//foo/qux}"
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Using
${str/a/b}and expecting all occurrences to be replaced, when only the first is; use${str//a/b}. - Expecting the original variable to change, when it only produces a new value.
- Forgetting to escape special characters in the pattern, such as
/.
🔒
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: