Extract file basename without path and extension in bash

neversaint picture neversaint · Apr 19, 2010 · Viewed 522.5k times · Source

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

ghostdog74 picture ghostdog74 · Apr 19, 2010

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.).

Source: Shell Command Language 2.6.2 Parameter Expansion

More on bash String Manipulations: http://tldp.org/LDP/LG/issue18/bash.html