Posted on August 14, 2023 by nexonhost
How To Use Basename Command.
basename is a command-line utility that strips directory and trailing suffix from given file names.
Using the basename Command
The basename command supports two syntax formats:
basename NAME [SUFFIX] basename OPTION... NAME...
basename takes a filename and prints the last component of the filename. Optionally, it can also remove any trailing suffix. It is a simple command that accepts only a few options.
The most basic example is to print the file name with the leading directories removed:
basename /etc/passwd
The output will include the file name:
passwd
The basename command removes any trailing / characters:
basename /usr/local/basename /usr/local
Both commands will produce the same output:
basename
By default, each output line ends in a newline character. To end the lines with NUL, use the -z (–zero) option.
Multiple Inputs
The basename command can accept multiple names as arguments. To do so, invoke the command with the -a (–multiple) option, followed by the list of files separated by space.
For example, to get the file names of /etc/passwd and /etc/shadow you would run:
basename -a /etc/passwd /etc/shadow
passwd shadow
Removing a Trailing Suffix
To remove any trailing suffix from the file name, pass the suffix as a second argument:
basename /etc/hostname name
host
Generally, this feature is used to strip file extensions:
basename /etc/sysctl.conf .conf
sysctl
Another way to remove a trailing suffix is to specify the suffix with the -s (–suffix=SUFFIX) option:
basename -s .conf /etc/sysctl.conf
sysctl
This syntax form allows you to strip any trailing suffix from multiple names:
basename -a -s .conf /etc/sysctl.conf /etc/sudo.conf
sysctl sudo
Example
The following example shows how to use the basename command inside a bash for loop to rename all files ending with “.jpeg” in the current directory by replacing the file extension from “.jpeg” to “.jpg”:
for file in *.jpeg; do mv -- "$file" "$(basename $file .jpeg).jpg" done
If you are using bash as your shell, instead of invoking basename, you can use strip the trailing extension using Shell Parameter Expansion .
Conclusion.
The basename command strips any leading directory and trailing suffix from the name.