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

String Replacement

In this page:

  1. String Replacement

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}"

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.