Skip to main content
  1. About
  2. Stack Internal
The 2026 Annual Developer Survey is live— take the Survey today!

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

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?

Answer*

Reminder: Answers generated by AI tools are not allowed due to Stack Overflow's artificial intelligence policy

Draft saved
Draft discarded

Required fields are marked with *

Cancel
18
  • 95
    Check out gnu.org/software/bash/manual/html_node/… for the full feature set.
    D.Shawley
    –  D.Shawley
    2009-06-08 14:08:51 +00:00
    Commented Jun 8, 2009 at 14:08
  • 27
    Add some quotes to "$fullfile", or you'll risk breaking the filename.
    lhunath
    –  lhunath
    2009-06-08 14:34:48 +00:00
    Commented Jun 8, 2009 at 14:34
  • 54
    Heck, you could even write filename="${fullfile##*/}" and avoid calling an extra basename
    ephemient
    –  ephemient
    2009-06-09 17:52:24 +00:00
    Commented Jun 9, 2009 at 17:52
  • 58
    This "solution" does not work if the file does not have an extension -- instead, the whole file name is output, which is quite bad considering that files without extensions are omnipresent.
    nccc
    –  nccc
    2012-07-01 03:42:00 +00:00
    Commented Jul 1, 2012 at 3:42
  • 53
    Fix for dealing with file names without extension: extension=$([[ "$filename" = *.* ]] && echo ".${filename##*.}" || echo ''). Note that if an extension is present, it will be returned including the initial ., e.g., .txt.
    mklement0
    –  mklement0
    2012-09-07 14:41:40 +00:00
    Commented Sep 7, 2012 at 14:41

lang-bash
Morty Proxy This is a proxified and sanitized view of the page, visit original site.