🎓 A1Learner
🔍
0 of 46 lessons completed

Bash Parameter Substitution

Parameter substitution replaces a matching pattern inside a value. One slash replaces the first match, and two slashes replace every match.

First match versus every match

The word one appears twice in the text. One slash changes only the first one, and two slashes change both.

text="one two one two"
echo "${text/one/1}"
echo "${text//one/1}"

Anchored to the start or the end

The # anchor only matches at the start, and the % anchor only matches at the end. A start anchor fails when the pattern sits elsewhere.

word="banana"
echo "${word/#ba/BA}"
echo "${word/%na/NA}"
echo "${word/#na/NA}"

Delete a match or replace a longer pattern

An empty replacement deletes every a from banana. The two-letter pattern na is then replaced in both places at once.

word="banana"
echo "${word//a/}"
echo "${word//na/NA}"

Example

title="draft-draft-report"
echo "${title/#draft/final}"
echo "${title//draft/final}"
echo "${title/%report/summary}"

Key points

  • ${var/pattern/replacement}: replace the first match only.
  • ${var//pattern/replacement}: replace every match.
  • ${var/#pattern/replacement}: replace only a match at the start.
  • ${var/%pattern/replacement}: replace only a match at the end.
  • Patterns are globs, not regular expressions.
  • Leaving the replacement out deletes the match.

In this example, the title holds the word draft twice and ends with report. The # form changes only the draft at the start. The // form changes both drafts. The % form changes only the report at the end.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does ${text//cat/dog} do?