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.
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:
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
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:
Now, to extract the filename, We will store the value in another value using bash parameter substitution. Run the following command:
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!