Clear Filters
Clear Filters

change file names in different folders within one same directory

1 view (last 30 days)
Hello, I want to change the file names within the folders that ends with *.nii, *bvec, *bvals for more than 10 folders. The following files are in that specific 10 folders. How to do that on matlab using system function? need help so badly!!
So as an example, I have 10 folders named with patient ID in one folder. Within the folder named patient ID, there are three files that I have to change the name.
What I want is, make a loop to get in one patient folder change three items' name, then come back out and move to next patient folder, do same thing, and so on.
E.g.
Patient ID folder : 00707MAY14
files : *.nii , *.bvec , *.bval
want to change the name with : 001nodif.nii.gz , 001.bvecs , 001.bvals (the number will sequentially increase as move on to next patient)

Answers (1)

Walter Roberson
Walter Roberson on 1 Aug 2019
dinfo = dir('*');
dinfo(ismember({dinfo.name}, {'.', '..'})) = []; %remove . and ..
dinfo(~[dinfo.isdir]) = []; %remove non-folders
foldernames = {dinfo.name};
for idx = 1 : length(foldernames)
thisfolder = foldernames{idx};
niifiles = dir( fullfile(thisfolder, '*.nii') );
if length(niifiles) == 1
oldname = fullfile(thisfolder, {niifiles.name});
newname = sprintf('%03dnodif.nii', idx);
movefile(oldname, newname);
gzip(newname);
else
warning('Unexpectedly, there are %d .nii files in directory "%s"', length(niifiles), thisfolder);
end
bvecfiles = dir( fullfile(thisfolder, '*.bvec') );
if length(bvecfiles) == 1
oldname = fullfile(thisfolder, {bvecfiles.name});
newname = sprintf('%03d.bvecs', idx);
movefile(oldname, newname);
else
warning('Unexpectedly, there are %d .bvec files in directory "%s"', length(bvecfiles), thisfolder);
end
bvalfiles = dir( fullfile(thisfolder, '*.bval') );
if length(bvalfiles) == 1
oldname = fullfile(thisfolder, {bvalfiles.name});
newname = sprintf('%03d.bvals', idx);
movefile(oldname, newname);
else
warning('Unexpectedly, there are %d .bval files in directory "%s"', length(bvalfiles), thisfolder);
end
end

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!