Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract filename and extension in Bash

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 927
ibz Avatar asked Jun 08 '09 14:06

ibz


People also ask

How do you segregate a basename and extension of a file in Linux?

Sometimes the users need to read the basename of the file only by removing the file extension. Filename and extension can be separated and stored on different variables in Linux by multiple ways. Bash built-in command and shell parameter expansion can be used to remove the extension of the file.

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 find the file extension in Linux?

To find out file types we can use the file command. Using the -s option we can read the block or character special file. Using -F option will use string as separator instead of “:”. We can use the –extension option to print a slash-separated list of valid extensions for the file type found.


1 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 143
Petesh Avatar answered Sep 29 '22 09:09

Petesh