我可以使用fileparts
获得不带扩展名的文件名
>> f = '/foo/bar/file.gz'
>> [~,filename,~] = fileparts(f)
filename =
'file'
但是,如果文件有多个扩展名,则只有最后一个扩展名会被删除
>>f = '/foo/bar/file.gz.tar'
>>[~,filename,~] = fileparts(f)
filename =
'file.gz'
我知道有多个点的文件扩展名是什么还不清楚,但有没有一种方法可以指定,例如,应该删除.gz
和.gz.tar
?
您总是可以手动搜索点:
[~,filename,~] = fileparts(f);
i = find(filename == '.', 1, 'first');
if ~isempty(i)
filename = filename(1:i - 1);
end
或者,您可以迭代fileparts
,直到它停止更改名称:
[~, filename, ~] = fileparts(f);
prev = '';
while ~strcmp(prev, filename)
prev = filename;
[~, filename, ~] = fileparts(prev);
end
如果你想删除一个确切的扩展,它会简单得多。只需检查名称是否以该序列结束,并根据需要去掉尽可能多的字符。对于.tar.gz
示例:
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];
这将删除所有扩展:
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
这只会删除选择的扩展:
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