Skip to content

Instantly share code, notes, and snippets.

@nimula
Created November 12, 2023 08:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nimula/385938957bb96234aa62abc6ed8f950e to your computer and use it in GitHub Desktop.
Save nimula/385938957bb96234aa62abc6ed8f950e to your computer and use it in GitHub Desktop.
Remove the extension of a filename, using POSIX's built-in script only.
#!/usr/bin/env sh
# Remove the extension of a filename, using POSIX's built-in script only.
# https://stackoverflow.com/a/63970495/4789973
path=this.path/with.dots/in.path.name/filename.tar.gz
# Get the basedir without external command
# by stripping out shortest trailing match of / followed by anything
dirname=${path%/*}
# Get the basename without external command
# by stripping out longest leading match of anything followed by /
basename=${path##*/}
# Strip uptmost trailing extension only
# by stripping out shortest trailing match of dot followed by anything
oneextless=${basename%.*}; echo "$oneextless"
# Strip all extensions
# by stripping out longest trailing match of dot followed by anything
noext=${basename%%.*}; echo "$noext"
# Printout demo
printf %s\\n "$path" "$dirname" "$basename" "$oneextless" "$noext"
@nimula
Copy link
Author

nimula commented Nov 12, 2023

Output:

this.path/with.dots/in.path.name/filename.tar.gz
this.path/with.dots/in.path.name
filename.tar.gz
filename.tar
filename

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment