filename


Bash: Get Filename, File Extension and Path from Full Path

The following commands will allow you extract various information from the full path of a file.

Part of the information is the filename, the file extension, the file base and the directory it is located in.

# Truncate the longest match of */ from the beginning of the string
filename="${fullpath##*/}";
# Get the sub-string from the start (position 0) to the position where the filename starts
directory="${fullpath:0:${#fullpath} - ${#filename}}";
# Strip shortest match of . plus at least one non-dot char from end of the filename
base="${filename%.[^.]*}";
# Get the sub-string from length of base to end of filename
extension="${filename:${#base} + 1}";
# If we have an extension and no base, it means we do not really have an extension but only a base
if [[ -z "$base" && -n "$extension" ]]; then
  base=".$extension";
  extension="";
fi
echo -e "Original:\t'$fullpath':\n\tdirectory:\t'$directory'\n\tfilename:\t'$filename'\n\tbase name:\t'$base'\n\textension:\t'$extension'"

Extract filename from full path filename / Get file extension

The first command strips down the full path filename to the filename only ising the basename command.

filename=$(basename $filenamefullpath)

Afterwards you can see how to extract the file extension from the filename.  There is no need to do this after issuing the above command since this command will just remove everything after the first from right dot (‘.’) — so make sure that the filename you are parsing has a dot or you will end up with wrong results (like the full path or a part of the full path if it contains a dot somewhere).

extension=${filename##*.}

Finally, by issuing the following command you remove everything after the first dot on the right (including).

filename=${filename%.*}