get a file's name, folder and extension

Take a path apart in a script: the folder, the name, the name without its extension, the extension.

  • shell
  • files
  • development

Steps

  1. file="${path##*/}"

    the name: /a/b/report.tar.gz → report.tar.gz

  2. dir="${path%/*}"

    the folder: /a/b

  3. ext="${file##*.}"

    the last extension: gz

  4. base="${file%.*}"

    the name without it: report.tar

  5. basename "$path" .gz

    the same with basename, ending removed

  6. dirname "$path"

    the folder, with dirname

Notes

  • ## and %% take the longest match, # and % the shortest: ${file%%.*} gives report.

Commands used

  • basename
  • dirname

Each has a page in lore: lore basename opens it.