Search code examples
matlabdirectoryfilenamesfile-rename

How to move from file to file in a loop, MatLab?


Is there a way to simply load the name of the first file in a directory without specifying its name, and then in each iteration move on to the next file in the directory?

I have the problem of the file names being named with 1, 1.5, 2,2.5,3, 3.5 endings etc... so num2str(X) in an iteration will not help to locate the file.

I am trying to rename them using strrep(s1,s2,s3), but yet again I run into the same problem of loading them into a loop!

I understand that I should have named them with more planning at first, but these files are much too large to run the simulations again.

This is what I have to rename the files:

%%%RENAMING A FILE%%%

%Search directory to get number of files
 d1=dir('\MATLAB\Data\NumberedQwQoRuns');
 numfiles = length(d1)-2;


for a=1:numfiles
%Search subdirectory if necessary for count of those folders
d2=dir('\MATLAB\Data\NumberedQwQoRuns\Run'num2str(a));
subdir = length(d2)-2;
for b= 1:subdir

origname= PROBLEM???

Newname=['Zdata' num2str(b) '.txt']
Newfile= strrep(origname, origname, newname)
movefile(origname,Newfile)

end
end

Thank You Very Much for your help, Abid A


Solution

  • Here is my solution:

    %# get runs subdirectories
    BASE_DIR = '/path/to/Runs';
    runsDir = dir( fullfile(BASE_DIR,'Runs') );
    runsDir = {runsDir([runsDir.isdir]).name};           %# keep only directory names
    runsDir = runsDir( ~ismember(runsDir, {'.' '..'}) ); %# ignore "." and ".."
    
    for r=1:numel(runsDir)
        %# get files in subdirectory
        runFiles = dir(fullfile(BASE_DIR,'Runs',runsDir{r},'*.txt')); %# *.txt files
        runFiles = {runFiles.name};                                   %# file names
    
        %# map filenames: 1,1.5,2,2.5,... into 1,2,3,4,...
        [~,ord] = sort(str2double( regexprep(runFiles,'\.txt$','') ));
        newrunFiles = cellstr( num2str(ord(:),'Zdata_%d.txt') );
        newrunFiles = strtrim(newrunFiles);
    
        %# rename files
        for f=1:numel(runFiles)
            fname = fullfile(BASE_DIR,'Runs',runsDir{r},runFiles{f});
            fnameNew = fullfile(BASE_DIR,'Runs',runsDir{r},newrunFiles{f});
            movefile(fname,fnameNew);
        end
    end
    

    I tested it on the following file structure:

    Runs/
    |
    |__Run1/
    |  |__1.txt        will become: Zdata_1.txt
    |  |__1.5.txt                   Zdata_2.txt
    |  |__2.txt                     Zdata_3.txt
    |  |__2.5.txt                   etc...
    |  |__3.txt
    |  |__3.5.txt
    |
    |__Run2/
       |__1.txt
       |__1.5.txt
       |__2.txt
       |__2.5.txt
       |__3.txt
       |__3.5.txt