HowTo: Bash Extract Filename And Extension In Unix / Linux

You can extract the filename and extension from a file path in bash using parameter expansion and string manipulation.

Here are a few examples of how to extract the filename and extension:

  1. Extract the filename and extension using parameter expansion:
path="/path/to/file.ext"
filename="${path##*/}"
extension="${filename##*.}"
echo "Filename: $filename"
echo "Extension: $extension"
  1. Extract the filename and extension using string manipulation:
path="/path/to/file.ext"
filename="${path##*/}"
extension="${filename#*.}"
echo "Filename: ${filename%.*}"
echo "Extension: $extension"

In both of these examples, the ##*/ parameter expansion operator is used to remove the leading /path/to/ from the file path. The ##*. operator is used to remove the text up to and including the last dot (.) in the filename. The #*. operator is used to remove the text up to the first dot (.) in the filename. The %.* operator is used to remove the extension from the filename.

Note: These methods assume that the file path contains only one dot (.), and that the dot separates the filename and extension. If the file path contains multiple dots, or the dots are part of the filename, the results may not be as expected.

Leave a Comment