How to check if file name has a certain ending?
Show older comments
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?
Accepted Answer
More Answers (2)
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 Comments
Azzi Abdelmalek
on 9 Aug 2014
it also returns subfolders
Yeah, that's correct w/ Matlab...I use JPSoft shell with aliases(*) to avoid that so tend to forget. Simple enough to take care of, however, ...
for i=1:length(dNoExt)
if dNoExt(i).isdir, continue, end % skip directory entries
movefile(dNoExt(i).name,[dNoExt(i).name '.yourextension']);
end
(*) The JPSoft command interpreters allow one to write aliases for builtin commands or other programs similarly to aliasing builtin Matlab functions.
C:\> alias dir
*dir /2hzlp /a:-d
C:\> alias ddir
*dir /a:d /hpw
So, if want directories, I use 'ddir', otherwise I'm never bothered by them cluttering up the file list returned. I've often wished TMW had implemented the additional features with dir, especially the attributes. Directories are ok, but the others aren't returned in the structure and altho not often needed, when are it's not particularly convenient. But, as above, having the facility and becoming accustomed to it for so long I occasionally forget not every application "does it right!" :)
Aaron
on 9 Aug 2014
dpb
on 9 Aug 2014
Note the simplification of eliminating the directory entries above if still interested...
Azzi Abdelmalek
on 9 Aug 2014
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)
Categories
Find more on File Operations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!