Search code examples
matlabsortingfor-loopdir

Odd numbering of files from one folder to other in matlab


Files present in one folder:

1 copy(1).jpg,

1 copy(2).jpg

.......

.......

.......

1 copy(800)

Odd numbering of files and save it in other folder.Desired output shown below:

1.jpg,

3.jpg,

5.jpg

....

....

....

799.jpg

Source code i tried:

a ='C:\Users\rahul\Desktop\jumbled test\copiedimages\';
A =dir( fullfile(a, '*.jpg') );
fileNames = { A.name };
for iFile = 1 : numel( A )
  newName = fullfile(a, sprintf( '%d.jpg',iFile+2) );
  movefile( fullfile(a, fileNames{ iFile }), newName ); 
end 

But i cant able to get desired output.So what will be the solution?


Solution

  • Don't rename the files, just move them to the new directory after checking if they had an odd number in their file name:

    a ='C:\Users\rahul\Desktop\jumbled test\copiedimages\';
    destination = a ='C:\Users\rahul\Desktop\jumbled test\copiedimages\Odd\';
    A =dir( fullfile(a, '*.jpg') );
    fileNames = { A.name };
    for iFile = 1 : numel( A )
        [~,name] = fileparts(fileNames{ iFile });  %// This part might not be necessary if fileNames{ iFile } is just the file name without the directory. In that case rather use name=fileNames{ iFile };
        %// Extract the number from the file name
        filenum = str2num(name(8:end-4));
        %// Check if the number is odd
        if mod(filenum,2) == 1 
            movefile(fullfile(a, fileNames{ iFile }), fullfile(destination, fileNames{ iFile }));
        end
    end