How to check if file name has a certain ending?

조회 수: 6 (최근 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 CenterFile Exchange에서 File Operations에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by