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 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:
The output will include the file name:
The basename command removes any trailing / characters:
Both commands will produce the same output:
By default, each output line ends in a newline character. To end the lines with NUL, use the -z (–zero) option.
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:
Removing a Trailing Suffix
To remove any trailing suffix from the file name, pass the suffix as a second argument:
Generally, this feature is used to strip file extensions:
Another way to remove a trailing suffix is to specify the suffix with the -s (–suffix=SUFFIX) option:
This syntax form allows you to strip any trailing suffix from multiple names:
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”:
If you are using bash as your shell, instead of invoking basename, you can use strip the trailing extension using Shell Parameter Expansion .
The basename command strips any leading directory and trailing suffix from the name.