Pattern Removal & Replace in Bash

From the Bash Scripting cheat sheet · Parameter Expansion · verified Jul 2026

Pattern Removal & Replace

Trim prefixes/suffixes and substitute.

bash
# Quick Reference
${file#*/}     # remove shortest leading match
${file##*/}    # remove longest (-> basename)
${file%.*}     # remove shortest trailing (-> drop ext)
${var/old/new} # replace first match
💡 # / ## strip from the FRONT (shortest/longest); % / %% strip from the BACK.
⚡ ${f##*/} is a fast pure-bash basename; ${f%/*} is a pure-bash dirname.
📌 ${v/old/new} replaces the first match; ${v//old/new} replaces all (double slash).
🟢 These run in-process - far faster than calling sed/basename in a loop.
parameter-expansionstring

More Bash tasks

Back to the full Bash Scripting cheat sheet