Bash: How to Get a Filename from a Path

bash get filename from path

If you are working with Bash, you may need to extract the filename from a given path. This can be useful if you need to rename or manipulate files within a script. Fortunately, Bash provides a simple way to get the filename from a path using built-in commands.

Basic Syntax

The basic syntax for getting the filename from a path in Bash is as follows:

${variable##*/}

In this syntax, variable is the path from which you want to extract the filename. The ##*/ syntax is known as a parameter expansion and it removes everything up to and including the last forward slash in the path, leaving only the filename.

Let’s take a closer look at how this works with some examples.

Example 1: Extracting a Filename from a Path

Suppose you have a file located at /home/user/documents/example.txt. To extract just the filename (example.txt) from this path, you can use the following command:

path="/home/user/documents/example.txt"
filename="${path##*/}"
echo $filename

The output of this command will be:

example.txt

Here, we first set the path variable to the full file path. Then, we use the ${path##*/} syntax to extract the filename and store it in a new variable called filename. Finally, we use echo to print the filename to the console.

Example 2: Renaming a File

Suppose you have a file called oldfile.txt located in the current directory, and you want to rename it to newfile.txt. You can use the mv command along with parameter expansion to accomplish this:

oldname="oldfile.txt"
newname="newfile.txt"
mv $oldname ${oldname%.*}.txt

In this example, we first set the oldname and newname variables to their respective values. Then, we use the ${oldname%.*} syntax to remove the file extension from the old filename. Finally, we use the mv command to rename the file, replacing the old filename with the new filename.

Conclusion

In Bash, getting the filename from a path is a simple task that can be accomplished using parameter expansion. By using this technique, you can easily manipulate filenames within your scripts and automate common tasks like renaming files.