How to Extract filename and extension in Bash?

Understand Extract filename and extension in Bash

Syntax

In Bash, you can extract the filename and extension from a file path using the following syntax:

filename="${path##*/}"
extension="${filename##*.}"
filename_no_ext="${filename%.*}"

Let's break down the syntax:

  • path is the variable that holds the file path.
  • "${path##*/}" extracts the filename from the path by removing everything up to and including the last forward slash.
  • "${filename##*.}" extracts the extension from the filename by removing everything up to and including the last dot.
  • "${filename%.*}" extracts the filename without extension by removing the shortest possible match of anything after the last dot.

Example

Here's an example that shows this in use:

path="/usr/local/bin/example.sh"
filename="${path##*/}"
extension="${filename##*.}"
filename_no_ext="${filename%.*}"
echo "Filename: $filename"
echo "Extension: $extension"
echo "Filename without extension: $filename_no_ext"

This will output:

Filename: example.sh
Extension: sh
Filename without extension: example
  1. Dynamic variable names in Bash
  2. How to parse command line arguments in Bash?
  3. Bash and shell script variable capitalization?
  4. How to get the directory where a Bash script is located from within the script itself?
  5. Parsing JSON with Unix tools
  6. Command not found error in Bash variable assignment
  7. How to set a variable to the output of a command in Bash?
  8. How to run Bash commands in Python? 9.Looping through the content of a file in Bash