How do I remove the file suffix and path portion from a path string in Bash?
Given a string file path such as /foo/fizzbuzz.bar
, how would I use bash to extract just the fizzbuzz
portion of said string?
Solution 1:
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.
Solution 2:
look at the basename command:
NAME="$(basename /foo/fizzbuzz.bar .bar)"
instructs it to remove the suffix .bar
, results in NAME=fizzbuzz
Solution 3:
Pure bash, done in two separate operations:
-
Remove the path from a path-string:
path=/foo/bar/bim/baz/file.gif file=${path##*/} #$file is now 'file.gif'
-
Remove the extension from a path-string:
base=${file%.*} #${base} is now 'file'.
Solution 4:
Using basename I used the following to achieve this:
for file in *; do
ext=${file##*.}
fname=`basename $file $ext`
# Do things with $fname
done;
This requires no a priori knowledge of the file extension and works even when you have a filename that has dots in it's filename (in front of it's extension); it does require the program basename
though, but this is part of the GNU coreutils so it should ship with any distro.