How do you strip prefixes and suffixes with parameter expansion?
IntermediateConceptVariables, quoting and expansions
Answer
# removes from the front, % from the back; single = shortest match, double = longest.
path=/var/backups/web1-20261109.tar.gz
echo "${path##*/}" # web1-20261109.tar.gz (basename)
echo "${path%/*}" # /var/backups (dirname)
f=${path##*/}
echo "${f%%.*}" # web1-20261109 (strip all extensions)
echo "${f%.gz}" # web1-20261109.tar
echo "${f#*-}" # 20261109.tar.gz
These run inside the shell with no fork, so they are much faster than calling basename in a loop over 10,000 files.
More on Variables, quoting and expansions
What are the rules for assigning variables in Bash?BeginnerWhat is the difference between single quotes, double quotes and `$'...'`?BeginnerWhy should you almost always quote variable expansions? Show what goes wrong.BeginnerExplain the difference between `"$@"`, `"$*"`, `$@` and `$*`.IntermediateWhat do `${var:-default}`, `${var:=default}`, `${var:+alt}` and `${var:?msg}` do?IntermediateHow do you do search-and-replace, substrings, length and case conversion without external tools?Intermediate