Bash: How to Extract Filename Without Extension from Path


Often you may want to extract a filename without the extension from a path in Bash.

There are two common ways to do so:

Method 1: Extract Filename Without Extension when Extension is Known

basename $my_path .txt

This particular example returns the filename without the extension from the path specified by the $my_path variable when it is known that the file has a .txt extension.

Method 2: Extract Filename Without Extension when Extension is Unknown

echo "$(x=${my_path##*/}; echo ${x%.*})"

This particular example returns the filename without the extension from the path specified by the $my_path variable when the extension of the file is unknown.

The following examples show how to use each method in practice.

Example 1: Extract Filename Without Extension when Extension is Known

Suppose that we have a file named teams.txt with the following file path:

  • c:/users/bobbi/teams.txt

Suppose that we would like to extract only the filename without the extension, which would be the following:

  • teams

Since we know that the extension is .txt for the file, we can use the following syntax:

my_path='/c/users/bobbi/teams.txt'

basename $my_path .txt

The following screenshot shows how to use this syntax in practice:

Bash extract filename without extension

Notice that this returns teams, which represents the filename without the extension.

Example 2: Extract Filename Without Extension when Extension is Unknown

Once again, suppose that we have a file named teams.txt with the following file path:

  • c:/users/bobbi/teams.txt

Again suppose that we would like to extract only the filename without the extension, which would be the following:

  • teams

Suppose that we don’t know the extension of this particular file.

We can use the following syntax to extract the filename without the extension:

my_path='/c/users/bobbi/teams.txt'

echo "$(x=${my_path##*/}; echo ${x%.*})"

The following screenshot shows how to use this syntax in practice:

Bash extract filename without extension example

Notice that this returns teams, which represents the filename without the extension.

Note: The x used in the code is simply a placeholder. Feel free to replace the character x with any other character that you would like.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: Count Number of Lines in Each File in Directory
Bash: How to Count Number of Folders in a Directory
Bash: How to Add Prefix to All Files in Directory
Bash: How to Add Prefix to All Files in Directory

Leave a Reply