Substituting strings

Substituting patterns in expansions can be done with the "${myvar/pattern/replacement/}" form:

bash$ promise='I'\''ll do it today.'
bash$ printf '%s\n' "${promise/today/tomorrow}"

This only replaces the first instance of the pattern. If you want to replace all instances of the pattern, use two slashes before the first pattern rather than just one:

bash$ promise='Yes, today. I'\''ll do it today.'
bash$ printf '%s\n' "${promise/today/tomorrow}"
Yes, tomorrow. I'll do it today.
bash$ printf '%s\n' "${promise//today/tomorrow}"
Yes, tomorrow. I'll do it tomorrow.

Note that the pattern being replaced uses the wildcard (globbing) syntax, with * matching multiple characters, and ? matching only one; it is not a regular expression ...

Get Bash Quick Start Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.