Interview Prep/Shell Scripting/Variables, quoting and expansions

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.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Variables, quoting and expansions