How do I remove the file suffix and path portion from a path string in Bash? How do I remove the file suffix and path portion from a path string in Bash? bash bash

How do I remove the file suffix and path portion from a path string in Bash?


Here's how to do it with the # and % operators in Bash.

$ x="/foo/fizzbuzz.bar"$ y=${x%.bar}$ echo ${y##*/}fizzbuzz

${x%.bar} could also be ${x%.*} to remove everything after a dot or ${x%%.*} to remove everything after the first dot.

Example:

$ x="/foo/fizzbuzz.bar.quux"$ y=${x%.*}$ echo $y/foo/fizzbuzz.bar$ y=${x%%.*}$ echo $y/foo/fizzbuzz

Documentation can be found in the Bash manual. Look for ${parameter%word} and ${parameter%%word} trailing portion matching section.


look at the basename command:

NAME="$(basename /foo/fizzbuzz.bar .bar)"

instructs it to remove the suffix .bar, results in NAME=fizzbuzz


Pure bash, done in two separate operations:

  1. Remove the path from a path-string:

    path=/foo/bar/bim/baz/file.giffile=${path##*/}  #$file is now 'file.gif'
  2. Remove the extension from a path-string:

    base=${file%.*}#${base} is now 'file'.