Remove prefixes and suffixes
How it works
Bash can remove a matching part of a string using shell patterns, without touching a file. ${p#pattern} removes the shortest matching prefix and ${p##pattern} the longest. ${p%pattern} removes the shortest matching suffix and ${p%%pattern} the longest. A pattern such as * matches any string here, including slash; these are string patterns, not directory traversal. If the pattern does not match the required edge, the value is unchanged. These operators return text; they do not assign or rename files.
Run each example separately in a noninteractive Bash 5.2 script in a fresh empty practice directory, with default options and C locale. Output is shown separately; do not enter it as code.
Shortest and longest prefix
path=docs/2026/report.txtprintf '%s' "${path#*/}" "${path##*/}"Expected stdout:
2026/report.txtreport.txtThe first match ends at the first slash; the longest ends at the last slash.
Shortest and longest suffix
name=report.final.txtprintf '%s' "${name%.*}" "${name%%.*}"Expected stdout:
report.finalreportThe shortest match is .txt; the longest is .final.txt.
No match
Expected stdout:
report.txtreport.txtNo suffix matches .csv; nothing is removed.
Common mistakes
# and % are anchored at opposite edges. Do not treat them as regex or a filesystem-aware basename implementation: trailing slashes and unusual names may need separate handling.
Practice
For path=docs/2026/report.final.txt, extract report.final.txt, then remove only its last extension. Compare removing the longest suffix starting with a dot.
Next: Replace patterns and change case