Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Extract file basename without path and extension in bash

file names like these:
/the/path/foo.txt
bar.txt


I expect to get:
foo
bar


Why doesn't work?
#!/bin/bash

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


What's the right approach to do it?
by

3 Answers

espadacoder11
You don't have to call the 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

Note that this solution should work in all recent (post 2004) POSIX compliant shells, (e.g. bash, dash, ksh, etc.).
pankajshivnani123
The basename command has two different invocations; in one, you specify just the path, in which case it gives you the last component, while in the other you also give a suffix that it will remove. So, you can simplify your example code by using the second invocation of basename. Also, be careful to correctly quote things:
fbname=$(basename "$1" .txt)
echo "$fbname"
kshitijrana14
A combination of basename and cut works fine, even in case of double ending like .tar.gz:
fbname=$(basename "$fullfile" | cut -d. -f1)

Login / Signup to Answer the Question.