フィルターのクリア

How to check if file name has a certain ending?

42 ビュー (過去 30 日間)
Aaron
Aaron 2014 年 8 月 9 日
コメント済み: Stelios Fanourakis 2018 年 4 月 30 日
In the current folder are some files, which do or don't have a filename extension. I would like to check, whether they already have the filename extension or not and add the extension, if necessary.
How do I check the filename extension?
  2 件のコメント
Azzi Abdelmalek
Azzi Abdelmalek 2014 年 8 月 9 日
Do you mean a specific extension?
Aaron
Aaron 2014 年 8 月 9 日
No, in general, although the extension in my case would be ".mat".

サインインしてコメントする。

採用された回答

Image Analyst
Image Analyst 2014 年 8 月 9 日
編集済み: Image Analyst 2014 年 8 月 9 日
Try this:
myFolder = 'C:\whatever';
if ~isdir(myFolder)
errorMessage = sprintf('Error: The following folder does not exist:\n%s', myFolder);
uiwait(warndlg(errorMessage));
return;
end
% Look for all files and add extension of .m if they are missing extension.
filePattern = fullfile(myFolder, '*.*');
allFiles = dir(filePattern);
for k = 1 : length(allFiles)
baseFileName = allFiles(k).name;
oldFullFileName = fullfile(myFolder, baseFileName);
fprintf(1, 'Now reading %s\n', oldFullFileName);
[folder, baseFileName, extension] = fileparts(baseFileName);
if isempty(extension)
% No extension, so add a .m extension
newBaseFileName = sprintf('%s.m', baseFileName);
newFullFileName = fullfile(myFolder, newBaseFileName);
movefile(oldFullFileName, newFullFileName);
fprintf(1, 'Renamed %s to %s\n', oldFullFileName, newFullFileName);
end
end
  2 件のコメント
Aaron
Aaron 2014 年 8 月 9 日
Thanks!
Stelios Fanourakis
Stelios Fanourakis 2018 年 4 月 30 日
Very helpful answer. Thanks a lot!

サインインしてコメントする。

その他の回答 (2 件)

dpb
dpb 2014 年 8 月 9 日
編集済み: dpb 2014 年 8 月 9 日
dNoExt=dir('*.');
Returns all files with no extension in CWD in the dir structure dNoExt. Process as
for i=1:length(dNoExt)
if dNoExt(i).isdir, continue, end % skip directory entries
movefile(dNoExt(i).name,[dNoExt(i).name '.yourextension']);
end
Or, one can cleanup the returned directory entries first before the loop as
dNoExt=dNoExt(~[dNoExt.isdir]); % retain only files in structure
  4 件のコメント
Aaron
Aaron 2014 年 8 月 9 日
Thanks!
dpb
dpb 2014 年 8 月 9 日
Note the simplification of eliminating the directory entries above if still interested...

サインインしてコメントする。


Azzi Abdelmalek
Azzi Abdelmalek 2014 年 8 月 9 日
d=dir('*.*')
e={d.name}'
f=e(~cellfun(@isdir,e))
ii=regexp(f,'\.+','match')
jj=find(cellfun(@isempty ,ii))
g1=f(jj)
g2=strcat(g1,'.ext')
cellfun(@(x,y) movefile(x,y),g1,g2)
  1 件のコメント
Aaron
Aaron 2014 年 8 月 9 日
I didn't try your code, because the other answers here seem a bit easier to me. But thank you for your answer!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeFile Operations についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by