how to change name of a file and save it in to a folder?
8 次查看(过去 30 天)
显示 更早的评论
Hi, I have a folder with so many files with these kind of names 'HB17158_MR_0A0CABC7_01_200_01_023.dcm' is there any command or program to change the name of these files in to for example '23' and save them ? with the same format '.dcm'
can anyone help ?
0 个评论
回答(1 个)
Adam
2014-8-7
编辑:Adam
2014-8-7
movefile( 'source', 'destination' )
should do that for you with some dir type access and file string manipulation on the folder contents to create your new destination names.
e.g. something like:
dirListing = dir;
files = dirListing( ~[dirListing.isdir] );
filenames = { files.name };
would give you a starting point. When I just tried it though that seems to leave '..' in the listing (I'm sure it didn't when I used it in the past) so you may have to filter out further what you don't want, then manipulate the remaining filenames as desired.
[pathstr,name,ext] = fileparts(filename)
will allow you to get the extension from a filename which you can then tag back onto your replacement filename though various forms of string manipulation or regular expression function could probably also retain the extension for you.
2 个评论
Adam
2014-8-7
If you have:
oldFilename = 'HB17158_MR_0A0CABC7_01_200_01_023.dcm';
then:
parts = strsplit( oldFilename, '_' );
newFilename = parts{end}
will give you your new filename. Then:
movefile( oldFilename, newFilename );
will do the rename for you.
This simple example assumes that your current directory is the one in which your old file is and where you want to save the new one. If not then you need to have the full path of your old file, use
[pathstr,name,ext] = fileparts( oldFilepath );
Run the above code on the name part, then:
newFilepath = [pathstr newFilename ext];
should give you the full path (again this assumes you want to rename in the same directory).
My example also assumes that all your files have a format such that they have some characters followed by '_' followed by the new shorter name you want (e.g. '_023').
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 File Operations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!