asked in Programming by (8.9k points) edited by
0 like 0 dislike

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
answered by (8.9k points) edited by

That gives you the file name, including the extension:

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

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

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:

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:

echo ${file##*/}

Get file name without path:

filename=$(basename -- "$fullfile")

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


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.

Related questions

0 like 0 dislike
1 answer 10 views
0 like 0 dislike
1 answer 15 views
0 like 0 dislike
1 answer 12 views
0 like 0 dislike
1 answer 12 views
0 like 0 dislike
1 answer 17 views
0 like 0 dislike
1 answer 41 views
0 like 0 dislike
1 answer 31 views