Remove certain extensions from filename with multiple extensions

Viewed 99

I can get the filename without extension using fileparts

>> f = '/foo/bar/file.gz'
>> [~,filename,~] = fileparts(f)
filename =

    'file'

However if the file has multiple extensions, only the last one will be removed

>>f = '/foo/bar/file.gz.tar'
>>[~,filename,~] = fileparts(f)
filename =

    'file.gz'

I know it's ambiguous what the file extension could be with multiple dots, but is there a way I can specify, for example, that both .gz and .gz.tar should be removed?

2 Answers

You can always search for dots manually:

[~,filename,~] = fileparts(f);
i = find(filename == '.', 1, 'first');
if ~isempty(i)
    filename = filename(1:i - 1);
end

Or you can iterate fileparts until it stops changing the name:

[~, filename, ~] = fileparts(f);
prev = '';
while ~strcmp(prev, filename)
    prev = filename;
    [~, filename, ~] = fileparts(prev);
end

If you are looking to remove an exact extension, it's much simpler. Just check if the name ends with that sequence, and strip off as many characters as you need. For the .tar.gz example:

ext = '.tar.gz';
n = numel(ext);
if numel(f) >= n && all(f(end - n + 1:end) == ext)
    f = f(1:end - n);
end
[~, filename, ext] = fileparts(f);
filename = [filename ext];

This removes all extensions:

f = '/foo/bar/file.gz.tar';
path = fileparts(f);                % get folder path
fileWithExt = erase(f,[path '/']);  % erase folder path from full path
fparts = strsplit(fileWithExt,'.'); % split string at dot
file = fparts{1};                   % get first entry

This only removes extensions of choice:

f = '/foo/bar/file.gz.tar.abc.xyz';
exts = {'tar','xyz'};               % extensions to remove

path = fileparts(f);                % get folder path
fileWithExt = erase(f,[path '/']);  % erase folder path from full path
fparts = strsplit(fileWithExt,'.'); % split string at dot
mask = ismember(fparts,exts);       % mask of extensions to remove
file = strjoin(fparts(~mask),'.');  % stitch string back together
Related