---
title: "How do I replace part of a string in a Bash variable?"
description: "Bash can replace, strip and trim text in a variable without calling sed. Learn the parameter expansion forms for replacing the first or every match and removing prefixes and suffixes."
url: https://www.danny.engineering/answer/bash/how-do-i-replace-part-of-a-string-in-a-bash-variable
author: Danny
published: 2026-11-27T00:00:00.000Z
updated: 2026-11-27T18:58:00.000Z
tags: ["Bash"]
---

# How do I replace part of a string in a Bash variable?

## The short answer


Use parameter expansion. `${var/old/new}` replaces the first match, `${var//old/new}` replaces every match, and `#`, `##`, `%` and `%%` remove text from the start or end. None of these change the original variable; they produce a new value you can assign.


```bash
file="report-draft-draft.txt"

echo "${file/draft/final}"    # report-final-draft.txt
echo "${file//draft/final}"   # report-final-final.txt
echo "${file%.txt}"           # report-draft-draft
echo "${file#report-}"        # draft-draft.txt
```


## Why it happens


Many people reach for `sed` or `tr` to edit a variable, which works but starts a new process for every call. That is slow inside a loop and adds quoting problems. Bash already has string editing built into variable expansion, so the work happens inside the shell.


The patterns in these expansions are glob patterns, the same kind you use for file names, not regular expressions. `*` matches any run of characters and `?` matches one character. Keeping that in mind explains most of the surprises people hit.


## How to fix it


### Replace the first or every match


One slash replaces the first match. Two slashes replace them all. Leave the replacement empty to delete the match.


```bash
path="/usr/local/bin:/usr/bin:/bin"

echo "${path/:/ }"     # /usr/local/bin /usr/bin:/bin
echo "${path//:/ }"    # /usr/local/bin /usr/bin /bin

phone="020 7946 0018"
echo "${phone// /}"    # 02079460018
```


### Anchor the match to the start or end


Add `#` or `%` after the first slash to replace only when the pattern is at the start or the end of the string.


```bash
url="http://example.com/http"

echo "${url/#http/https}"   # https://example.com/http
echo "${url/%http/home}"    # http://example.com/home
```


### Remove a prefix or suffix


`#` removes the shortest match from the start and `##` removes the longest. `%` and `%%` do the same from the end. These are ideal for file names and paths.


```bash
file="/var/log/app/server.log.gz"

echo "${file##*/}"    # server.log.gz   (like basename)
echo "${file%/*}"     # /var/log/app    (like dirname)
echo "${file%.*}"     # /var/log/app/server.log
echo "${file%%.*}"    # /var/log/app/server
```


A handy way to remember which is which: on a US keyboard `#` sits to the left of `$` and `%` sits to the right, so `#` trims the left and `%` trims the right.


### Rename files in a loop


Combining these with a loop gives you a quick bulk rename without extra tools.


```bash
for f in ./*.jpeg; do
  mv -- "$f" "${f%.jpeg}.jpg"
done
```


### Change case


Bash 4 and later can also change case: `^^` for upper case and `,,` for lower case.


```bash
name="Ada Lovelace"
echo "${name^^}"   # ADA LOVELACE
echo "${name,,}"   # ada lovelace
```


### Use sed for regular expressions


If you need capture groups, character classes beyond globs, or edits across a whole file, use `sed` instead. For a single variable that looks like this:


```bash
version="v2.14.3"
major=$(sed -E 's/^v([0-9]+)\..*/\1/' <<< "$version")
echo "$major"   # 2
```


Bash's own `[[ $var =~ regex ]]` test with `BASH_REMATCH` is another option that avoids a subprocess.


## Common pitfalls

- **Expecting a regex.** `${var//[0-9]+/X}` does not mean "one or more digits". In a glob, `+` is a literal plus sign. Use `${var//[0-9]/X}` to replace each digit, or switch to `sed -E`.
- **The original is not changed.** Write `file="${file//draft/final}"` if you want to keep the result.
- **`&`** **in the replacement.** From Bash 5.2 the `patsub_replacement` option is on by default, so an unquoted `&` in the replacement stands for the matched text. Quote it or escape it as `\&` when you mean a literal ampersand.
- **Special characters in the pattern.** If the text you are searching for comes from a variable and may contain `*`, `?` or `[`, quote it: `${var//"$needle"/x}`. Without quotes it is treated as a pattern.
- **macOS ships Bash 3.2.** The default `/bin/bash` on macOS has no `^^` or `,,`. Install a newer Bash with Homebrew or use `tr` there.
- **Forgetting quotes around the expansion.** `echo ${file%.txt}` still word-splits on spaces. Keep the double quotes.

## Related reading

- [GNU Bash manual: Shell parameter expansion](https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html)
