Skip to content
Related Articles

Related Articles

Extract Filename From the Full Path in Linux

View Discussion
Improve Article
Save Article
  • Last Updated : 03 Jun, 2022
View Discussion
Improve Article
Save Article

Linux is a family of open-source operating systems and comes as various distributions or distros. The full path in Linux means starting from the root directory “/”, the address of the file includes the directories and subdirectories until the file name.

A full file path in Linux looks as follows:

/home/user/Documents/test.txt

It always starts with a “/” and ends with the file name. When dealing with a single file, it is quite easy to get the file name but when a large number of filenames is required from their path, we can automate it. In this article, we will learn different ways to extract file names.

  • Using the basename command
  • Using Bash parameter substitution

Let’s go through all the methods one by one.

Method 1: Using the basename command

The basename command is solely created for the purpose of extracting the base name, that is the file name. Enter the following command in the following pattern to get the file name

basename full_path

Example:

basename /home/user/Desktop/exam1.pdf

Output:

 

Multiple paths: Use the -a flag to pass multiple paths and retrieve their file names respectively.

basename -a /home/user/Desktop/exam1.pdf /home/user/Desktop/exam2.pdf /home/user/Desktop/exam3.pdf

Output:

 

Method 2: Using Bash parameter substitution

In this method, we store the path in a variable, and then remove the part of the path before the last “/” using the following command.

$ filepath="/home/user/Desktop/exam1.pdf"
$ filename=${filepath##*/}
$ echo $filename

Output:

 

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!