brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: ${file%.*} and ${file##*/} trim a shell variable without sed

Shell
~/tips/tip-shell-param-trim-suffix-prefix

f=/srv/media/holiday.final.mp4

Strips an extension or a directory from a variable with built-in pattern removal.

Cutting an extension or a directory off a path does not need a second process.

f=/srv/media/holiday.final.mp4
echo "${f%.*}"   # /srv/media/holiday.final
echo "${f##*/}"  # holiday.final.mp4
echo "${f%%.*}"  # /srv/media/holiday

% removes the shortest match from the end, %% the longest. # and ## do the same from the start. The pattern is a glob, not a regex, so .* means a dot followed by anything. ${f##*/} is basename and ${f%/*} is dirname, without starting a program. These work in bash, zsh and any POSIX shell.

Further reading: Bash manual: Shell Parameter Expansion

More Shell tips zmv -n '(*).log' '$1.txt' zoxide query -ls project f=$(mktemp --suffix=.json) shopt globskipdots echo $EPOCHSECONDS All Shell tips (78) All topics

Link