← Back to Bash Course | Chapter 5: Functions | Lesson 5 of 11

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:

  1. String Replacement
Syntax
bash
${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

bash
#!/bin/bash
text="foo bar foo baz"
echo "${text/foo/qux}"
echo "${text//foo/qux}"
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
  1. Using ${str/a/b} and expecting all occurrences to be replaced, when only the first is; use ${str//a/b}.
  2. Expecting the original variable to change, when it only produces a new value.
  3. Forgetting to escape special characters in the pattern, such as /.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.