neversaint neversaint - 4 months ago 28
Linux Question

Extract File Basename Without Path and Extension in Bash

Given file names like these:

/the/path/foo.txt
bar.txt


I hope to get

foo
bar


Why this doesn't work?

#!/bin/bash

fullfile=$1
fname=$(basename $fullfile)
fbname=${fname%.*}
echo $fbname


What's the right way to do it?

Answer

You don't have to call external basename command. Instead, you could use the following commands:

$ s=/the/path/foo.txt
$ echo ${s##*/}
foo.txt
$ s=${s##*/}
$ echo ${s%.txt}
foo
$ echo ${s%.*}
foo

(From here) even though the OP is specifically about BASH, it is important to emphasize that the above commands use the BASH Shell Parameter Expansion and may not work in other shells.

Comments