⇠ Back to the blog
Cover for How to extract a filename and extension in Bash

How to extract a filename and extension in Bash

Christian Nguyen avatarWritten by Christian Nguyen

Method 1 - Using Basename

The first method we'll discuss for extracting a filename and extension in Bash is using the basename command. The basename command is used to strip directory information and suffixes from filenames. We can use the basename command to extract a filename from a path like so:

As you can see, this strips off the directory information (/path/to/) and returns only the filename (file.txt).

To also strip off the extension, we can use the basename command with the -s option like so:

This will return only the filename without the extension (.txt).

Method 2 - Using substring expansion

Another method we can use for extracting a filename and extension in Bash is using substring expansion. Bash provides a way to expand a string into multiple substrings based on a given delimiter.

We can use this functionality to our advantage by setting the delimiter to be '.' (the character that separates a filename from its extension). We can then use parameter expansion to access different parts of the string. For example, if we have a string stored in a variable named 'foo':

foo="/path/to/file.txt"

We could access only the filename like so:

${foo%.*} # Will return /path/to/file

And we could access only the extension like so:

${foo#*.} # Will return txt

Method 3 - Using AWK / sed Commands

Finally, we can also use AWK or sed commands to extract a filename or extension in Bash. These are both text processing tools that are commonly used in Linux for performing various operations on strings and files.

To extract only the filename using awk, we could do something like this:

awk -F'/' '{print $NF}' /path/to/file.txt # Will return file.txt

And to extract only the extension, we could do something like this:

sed 's/.*\(\.[^.]*\)/\1/' /path/to/file.txt # Will return .txt

You can save useful shell shortcuts like this, and a whole lot more, with Cased. If you're interested and want to learn more schedule a demo or visit our documentation.