in Programming by (9.9k points) edited by
0 like 0 dislike
24 views

How would I can to get just file name without extension from a path in a bash script? I want to get the filename without extension, and extension separately. How to get filename and extension in bash?


bash get filename to variable

1 Answer

0 like 0 dislike
by (9.9k points) edited by

That gives you the file name, including the extension:

a='/tmp/file.txt'
b=$(basename $a)
echo $b # file.txt

This method that can strip off the path and the extension:

a='/tmp/xx/file.tar.gz'
xpath=${a%/*} 
xbase=${a##*/}
xfext=${xbase##*.}
xpref=${xbase%.*}
echo;echo path=${xpath};echo pref=${xpref};echo ext=${xfext}

# path=/tmp/xx
# pref=file.tar
# ext=gz

Here variable xpath - file path, xpref - file prefix, what you were specifically asking, and xfext - file extension.


Standard basename and dirname commands are more convenient, but those are alternative solutions:

FILE_PATH="/opt/datastores/sda2/test.old.img"
echo "$FILE_PATH" | sed "s/.*\///"

This returns "test.old.img" like basename. This is salt filename without extension:

echo "$FILE_PATH" | sed -r "s/.+\/(.+)\..+/\1/"

It returns "test.old". And following statement gives the full path like dirname command:

echo "$FILE_PATH" | sed -r "s/(.+)\/.+/\1/"

It returns "/opt/datastores/sda2".


file=${$(basename $file_path)%.*}

Output filename without extension:

file=${path%.*}
echo ${file##*/}

Get file name without path:

filename=$(basename -- "$fullfile")
extension="${filename##*.}"
filename="${filename%.*}"

Alternatively, you can focus on the last '/' of the path instead of the '.' which should work even if you have unpredictable file extensions:

filename="${fullfile##*/}"

FILE="example.tar.gz"
echo "${FILE%%.*}" # example
echo "${FILE%.*}" # example.tar
echo "${FILE#*.}" # tar.gz
echo "${FILE##*.}" # gz

Your answer

Try to answer the question as detailed as possible.
Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.