More Bash answers

by Danny
Published 2 min read

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.

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.


_10
file="report-draft-draft.txt"
_10
_10
echo "${file/draft/final}" # report-final-draft.txt
_10
echo "${file//draft/final}" # report-final-final.txt
_10
echo "${file%.txt}" # report-draft-draft
_10
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.


_10
path="/usr/local/bin:/usr/bin:/bin"
_10
_10
echo "${path/:/ }" # /usr/local/bin /usr/bin:/bin
_10
echo "${path//:/ }" # /usr/local/bin /usr/bin /bin
_10
_10
phone="020 7946 0018"
_10
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.


_10
url="http://example.com/http"
_10
_10
echo "${url/#http/https}" # https://example.com/http
_10
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.


_10
file="/var/log/app/server.log.gz"
_10
_10
echo "${file##*/}" # server.log.gz (like basename)
_10
echo "${file%/*}" # /var/log/app (like dirname)
_10
echo "${file%.*}" # /var/log/app/server.log
_10
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.


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

Change case

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


_10
name="Ada Lovelace"
_10
echo "${name^^}" # ADA LOVELACE
_10
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:


_10
version="v2.14.3"
_10
major=$(sed -E 's/^v([0-9]+)\..*/\1/' <<< "$version")
_10
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.
#

Was this resource helpful?