Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script: remove extension from file name [duplicate]

I want to get the filename (without extension) and the extension separately.

The best solution I found so far is:

NAME=`echo "$FILE" | cut -d'.' -f1` EXTENSION=`echo "$FILE" | cut -d'.' -f2` 

This is wrong because it doesn't work if the file name contains multiple . characters. If, let's say, I have a.b.js, it will consider a and b.js, instead of a.b and js.

It can be easily done in Python with

file, ext = os.path.splitext(path) 

but I'd prefer not to fire up a Python interpreter just for this, if possible.

Any better ideas?

like image 841
ibz Avatar asked Jun 08 '09 14:06

ibz


People also ask

How do I remove a filename extension in Bash?

Remove File Extension Using the basename Command in Bash If you know the name of the extension, then you can use the basename command to remove the extension from the filename. The first command-Line argument of the basename command is the variable's name, and the extension name is the second argument.

How do you remove a filename extension in Unix?

You should be using the command substitution syntax $(command) when you want to execute a command in script/command. name=$(echo "$filename" | cut -f 1 -d '. ')


2 Answers

First, get file name without the 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##*/}" 

You may want to check the documentation :

  • On the web at section "3.5.3 Shell Parameter Expansion"
  • In the bash manpage at section called "Parameter Expansion"
like image 139
Petesh Avatar answered Oct 05 '22 22:10

Petesh


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

For more details, see shell parameter expansion in the Bash manual.

like image 25
Juliano Avatar answered Oct 05 '22 23:10

Juliano