Clear Filters
Clear Filters

how to change name of a file and save it in to a folder?

15 views (last 30 days)
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 ?

Answers (1)

Adam
Adam on 7 Aug 2014
Edited: Adam on 7 Aug 2014
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 Comments
Faranak
Faranak on 7 Aug 2014
I didn't understand it clearly, can you give me example with my files name? changing HB17158_MR_0A0CABC7_01_200_01_023.dcm to 23.dcm
Adam
Adam on 7 Aug 2014
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').

Sign in to comment.

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!