Linux basename command
The Linux basename command is used to strip directory and suffix from filenames. It is a handy tool for manipulating file paths and extracting specific parts of a file name. By using this command, you can easily isolate the base name of a file, which can be useful for various scripting and automation tasks. The basename command can be customized to remove a specified suffix or only display a specific part of the file name. This command is particularly helpful when working with large numbers of files or when needing to process file names in a consistent manner. Familiarizing yourself with the basename command can streamline your workflow and make file manipulation tasks more efficient.
basename Syntax:
Options:
Option | Description |
---|---|
-a | Support multiple arguments |
-s | Remove the suffix STRING |
-z | Separate output by NULL byte |
— | Treat all further arguments as file names (even if they start with ’-‘) |
Parameters:
Parameter | Description |
---|---|
string | The string from which to extract base name |
path | The path for which to extract the base name |
basename Usage:
Extract the file name from a path
This command will output “example.txt”.
Strip file extension from a file name
The output will be “document”.
Get only the directory name from a path
Will return “Documents”.
Extract the last element from a path
The result will be “file.txt”.
How do I use basename in Linux?
To use the basename command in Linux, execute the following command:
How can I get the filename without its full path using basename?
To extract just the filename without the directory path, you can use the basename command with the file path as shown below:
How do I remove the file extension using basename in Linux?
To remove the file extension from a filename, you can use the basename command along with the appropriate options. Here’s an example:
How can I remove multiple file extensions using basename?
You can remove multiple file extensions from a filename using the basename command with the -a option. Here’s an example:
How can I remove a suffix from a filename using basename?
To remove a specific suffix from a filename, you can use the basename command with the -s option followed by the suffix to be removed. Here’s an example:
How do I use basename to extract the directory path of a file?
If you need to extract the directory path of a file using basename, you can do so by providing the full file path. Here’s an example:
How can I handle filenames with spaces when using basename in Linux?
When working with filenames that contain spaces, make sure to enclose the file path in quotes to avoid any issues. Here’s an example:
Applications of the basename Command
- Stripping directory and suffix from filenames
- Parsing filenames in shell scripts
- Manipulating file paths in scripts
- Extracting a specific part of a file path