The “basename” takes a filename and prints the filename’s last portion. It can also delete any following suffix if needed.
Let’s use different examples to understand the basename command in Linux.
Syntax:
It supports two syntaxes:
- basename Path Suffix
- basename option pathname
In the first syntax, add a suffix at the end of path/filename, and in the second, we can add an option. We cannot add an option with a suffix.
Using basename command with filename:
Create the file by using the touch command:
In this example, the file is named bash.txt:
Now, let’s use the file with the basename command:
It will print the filename only.
Removing any / trailing character:
Use the following command to remove any trailing/character from the path:
Remove trailing suffix:
Transfer the suffix as a second argument to delete any trailing suffix from the file name:
Normally, this command is used to remove file extension:
Another way is to remove the trailing suffix from the file:
Print or remove multiple files:
We can print or remove multiple file suffixes from files by using the -a flag. To print multiple filenames, use the following command:
We can also remove trailing suffixes from multiple files by using the below command:
Conclusion:
A basename is a command-line tool that removes the directory and suffix from assigned file names. The basename command print the last portion of the file name on the terminal. This post describes the basename command in detail.