brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: ${var//old/new} replaces every match inside a bash variable

Bash
~/tips/tip-bash-pattern-substitution-replace-all

f="my holiday photo.jpg"

Swaps text inside a bash variable, once or everywhere, without calling sed.

Piping a variable through sed just to swap one character for another is a habit I see in a lot of scripts. Bash can do that by itself, inside the variable, and it reads a lot cleaner once you know the four little forms.

With one slash, bash replaces the first match of a pattern. With two slashes, it replaces all of them:

f="my holiday photo.jpg"
echo "${f/ /_}"     # my_holiday photo.jpg
echo "${f// /_}"    # my_holiday_photo.jpg

There are also ${var/#pattern/new}, which only matches at the start, and ${var/%pattern/new}, which only matches at the end. Leave the replacement empty and the match is simply deleted, so ${f// /} strips every space. The pattern is a glob, the same kind you use for file names, so * and ? work too.

A practical one: turning a path into something you can use as a file name for a backup or a log.

src=/mnt/user/appdata/jellyfin
name="${src#/}"          # drop the leading slash
tar -czf "/mnt/user/backup/${name//\//-}.tar.gz" "$src"
# writes mnt-user-appdata-jellyfin.tar.gz

To replace a slash you have to escape it as \/, otherwise bash thinks the pattern ends there.

The catch is a newer one. Since bash 5.2 the shell option patsub_replacement is on by default, and it makes an unquoted & in the replacement stand for the text that matched. So x=cats; echo "${x//cat/[&]}" prints [cat]s, where older bash printed [&]s. If you want a literal ampersand, write \& or quote that part of the replacement. My advice is to keep this in mind when a script that builds URLs or query strings moves to a newer system.

Further reading: bash(1) manual page, Bash NEWS (new features per version)

More Bash tips echo {01..10} cmd > file 2>&1 export HISTIGNORE='ls*:pwd:cd*' #rsync -av --delete /srv/media/ /mnt/backup/media/ APP_HOST=example.com All Bash tips (52) All topics

Link