Replace patterns and change case
How it works
${p/pattern/replacement} replaces the first matching part, whereas ${p//pattern/replacement} replaces every match. ${p/#pattern/replacement} restricts matching to the beginning and ${p/%pattern/replacement} to the end. Patterns follow Bash pattern rules, not regular expressions. For Bash 4.0+ case conversion, ${p^} and ${p,} change the first character if appropriate; ${p^^} and ${p,,} convert all applicable characters. An optional shell pattern limits conversion to matching characters; the pattern is tested against one character at a time, so it should not attempt to match more than one character. Case behavior depends on locale. These transformations do not assign back to p. Bash 5.2 also has patsub_replacement: an unquoted ampersand in replacement represents the matched text when that option is enabled. Quoting the entire parameter expansion does not by itself quote the replacement internally. For example, with p=red and r='&-x', "${p/red/$r}" produces red-x, whereas "${p/red/"$r"}" produces &-x. Quote the replacement expansion inside the braces for literal data; do not treat arbitrary replacement text as code.
Run each example separately in a noninteractive Bash 5.2 script in a fresh empty practice directory, with default options and C locale. Output is shown separately; do not enter it as code.
First versus all
tag=red-red-blueprintf '%s' "${tag/red/green}" "${tag//red/green}"Expected stdout:
green-red-bluegreen-green-blueA second slash changes replacement scope.
Replace only at an edge
tag=dev-app-devprintf '%s' "${tag/#dev/prod}" "${tag/%dev/prod}"Expected stdout:
prod-app-devdev-app-prodThe prefix and suffix forms restrict where the pattern matches.
Case conversion
Expected stdout:
BaShBASHbaShbashSingle operators examine only the first character; doubled operators examine all characters.
Common mistakes
One slash does not replace every occurrence. Quote the result, and explicitly assign it if you want to keep it. Do not expect modern case operators to work in Bash 3.2.
Practice
Given tag=Draft-Draft, replace all Draft with final, convert the result to uppercase, and store it in a separate variable. Leave tag unchanged.
Next: Indirect and transformation expansions