Bash Programming

Get Extract Filename From Path in Bash

“During Bash programming and particularly while working with files, you have to parse the file names every now and then. To be able to do that, you should be familiar with all the different ways in which you can get the desired file name from the given information. In this guide, we will show you how you can extract the filename from a path in Bash.”

How to Extract the Filename From a Given Path in Bash?

To extract the filename from any given path in Bash, you can use either of the two methods shared below:

Method # 1: The “basename” Command in Bash

In this method, we will be using the “basename” command in Bash to extract the filename from a given path. To be able to do so, we will run this command as follows:

$ basename /home/system/TestFolder/testfile.txt

In this command, the “basename” keyword is followed by the complete path of the file from which we have to extract the filename.

This command simply discards everything till the last “/,” hence retaining only the filename along with its associated extension. As soon as we hit the Enter button after typing this command in the terminal, the name of the file will instantly appear on the terminal, as shown in the image below:

Method # 2: The Parameter Substitution in Bash

In this method, we will be using the parameter substitution technique in Bash to extract the name of a file from a given path. For that, we will first save the complete path of that file in a Bash variable as given in the following command:

$ path=“/home/system/TestFolder/testfile.txt”

This command will save the path of our target file to the “path” variable.

After doing this, we will create another variable named “filename” and perform the parameter substitution in Bash with the help of the command shown below:

$ filename=${path##*/}

This command will extract the filename from the given path and will store it inside the “filename” variable. However, both of the above-mentioned commands will not produce any output on the terminal.

Now, to see the extracted filename on the terminal, you will have to run the following command:

$ echo $filename

This command will display the filename stored within the “filename” Bash variable as shown in the image below:

Conclusion

Both of the two methods explained above can conveniently extract the filename from any given path in Bash. Now, it is entirely up to you to use the method that you like the best for extracting the name of your desired file in Linux.

Similar Posts