How to extract the filename without the extension from a full path?

47,116

Solution 1

The usual way to do this in bash is to use parameter expansion. (See the bash man page and search for "Parameter Expansion".)

a=${1%.*}

The % indicates that everything matching the pattern following (.*) from the right, using the shortest match possible, is to be deleted from the parameter $1. In this case, you don't need double-quotes (") around the expression.

Solution 2

If you know the extension, you can use basename

$ basename /home/jsmith/base.wiki .wiki
base

Solution 3

One-liner in Bash without using basename:

$ s=/the/path/foo.txt
$ echo "$(b=${s##*/}; echo ${b%.*})"
foo
Share:
47,116

Related videos on Youtube

user304822
Author by

user304822

Updated on September 18, 2022

Comments

  • user304822
    user304822 over 1 year

    I'm trying to right my first bash script, and at one point a filename is passed to the script as $1. I need to extract the file name without the extension.
    Currently, I'm assuming that all extensions are three letters so I remove the last 4 characters to get the file name:

    a="${1:0:-4}"
    

    But I need to be able to work with extensions that have more than three characters, like %~n1 in Windows.
    Is there any way to extract the file name without the extension from the arguments?

  • user304822
    user304822 about 10 years
    The file patterns are generally like this: "Something.eng.ext". Obviously in this case ext is the extension, but using ${1%.*} will return only the "Something" part, right?
  • garyjohn
    garyjohn about 10 years
    No. ${1%.*} will return Something.eng. If you want to strip off everything to the right of the first . including the ., use ${1%%.*}, which will return Something.