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


Question

Given a string file path such as /foo/fizzbuzz.bar, how would I use bash to extract just the fizzbuzz portion of said string?

1
356
10/24/2018 9:42:46 PM

Accepted Answer

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.

505
10/14/2016 2:36:17 PM

look at the basename command:

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon