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
11
  • 45
    You (perhaps unintentionally) bring up the excellent question of what to do if the "extension" part of the filename has 2 dots in it, as in .tar.gz... I've never considered that issue, and I suspect it's not solvable without knowing all the possible valid file extensions up front.
    rmeador
    –  rmeador
    2009-06-08 14:50:20 +00:00
    Commented Jun 8, 2009 at 14:50
  • 11
    Why not solvable? In my example, it should be considered that the file contains two extensions, not an extension with two dots. You handle both extensions separately.
    Juliano
    –  Juliano
    2009-06-08 15:20:49 +00:00
    Commented Jun 8, 2009 at 15:20
  • 33
    It is unsolvable on a lexical basis, you'll need to check the file type. Consider if you had a game called dinosaurs.in.tar and you gzipped it to dinosaurs.in.tar.gz :)
    porges
    –  porges
    2009-06-13 09:11:04 +00:00
    Commented Jun 13, 2009 at 9:11
  • 14
    This gets more complicated if you are passing in full paths. One of mine had a '.' in a directory in the middle of the path, but none in the file name. Example "a/b.c/d/e/filename" would wind up ".c/d/e/filename"
    Walt Sellers
    –  Walt Sellers
    2012-03-05 18:49:56 +00:00
    Commented Mar 5, 2012 at 18:49
  • 20
    clearly no x.tar.gz's extension is gz and the filename is x.tar that is it. There is no such thing as dual extensions. i'm pretty sure boost::filesystem handles it that way. (split path, change_extension...) and its behavior is based on python if I'm not mistaken.
    v.oddou
    –  v.oddou
    2013-11-26 07:29:17 +00:00
    Commented Nov 26, 2013 at 7:29

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