Extract Filename From the Full Path in Linux

How To Extract Filename From The Full Path In Linux

Hey guys, In this article, We will discuss how to get the filename from the full path in Linux. The full path means the address at which the file is located. This includes all the directories and subdirectories. For example, We have a file named file1.txt. Its complete address will be /home/sid/Desktop/test/file1.txt. You can also check the complete address through the properties window.

extract-filename-1

Let’s see how to extract the filename from the full path using the following commands:

1. Using basename command

basename command is used to print the name while removing the directory components if any. Open a terminal by pressing Ctrl+Alt+T and execute the following command to extract the filename from the full path:

basename <file_path>
basename /home/sid/Desktop/test/file1.txt
extract-filename-2

If you want to extract multiple filenames, use -a for multiple arguments support and execute the following command:

basename -a /home/sid/Desktop/test/file1.txt /home/sid/Desktop/test/abc.sh
extract-filename-3

2. Using bash parameter

Bash is a command language interpreter which reads from standard input or a file. To extract the filename, Execute the following command to store the file path in a variable:

path="/home/sid/desktop/test/file1.txt"

Now, to extract the filename, We will store the value in another value using bash parameter substitution. Run the following command:

filename=${fullpath##*/}
echo $filename
extract-filename-4

Conclusion

So, We discussed how to extract the filename from the full path in Ubuntu 21.10. If you have multiple files, it is better to use the basename command to extract filenames. Thank you for Reading!