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.
_10file="report-draft-draft.txt"_10_10echo "${file/draft/final}" # report-final-draft.txt_10echo "${file//draft/final}" # report-final-final.txt_10echo "${file%.txt}" # report-draft-draft_10echo "${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.
_10path="/usr/local/bin:/usr/bin:/bin"_10_10echo "${path/:/ }" # /usr/local/bin /usr/bin:/bin_10echo "${path//:/ }" # /usr/local/bin /usr/bin /bin_10_10phone="020 7946 0018"_10echo "${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.
_10url="http://example.com/http"_10_10echo "${url/#http/https}" # https://example.com/http_10echo "${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.
_10file="/var/log/app/server.log.gz"_10_10echo "${file##*/}" # server.log.gz (like basename)_10echo "${file%/*}" # /var/log/app (like dirname)_10echo "${file%.*}" # /var/log/app/server.log_10echo "${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.
_10for f in ./*.jpeg; do_10 mv -- "$f" "${f%.jpeg}.jpg"_10done
Change case
Bash 4 and later can also change case: ^^ for upper case and ,, for lower case.
_10name="Ada Lovelace"_10echo "${name^^}" # ADA LOVELACE_10echo "${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:
_10version="v2.14.3"_10major=$(sed -E 's/^v([0-9]+)\..*/\1/' <<< "$version")_10echo "$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 tosed -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 thepatsub_replacementoption 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/bashon macOS has no^^or,,. Install a newer Bash with Homebrew or usetrthere. - Forgetting quotes around the expansion.
echo ${file%.txt}still word-splits on spaces. Keep the double quotes.
Related reading
#Was this resource helpful?