Clear Filters
Clear Filters

How to move/copy files from folder and subfolders to a new folder?

24 views (last 30 days)
I am trying to move/copy files from a main folder with multiple subfolders to a new folder.
The code below runs but I receive this error when I use this is in the loop...
for k = 1:numel(FilesName):
Error using movefile
No matching files were found.
Here is my attempt...
clear all, close all,
% Folders/subfolders where files are located
% I want to move only the .png files located under D:\2015\
myDir = dir('D:\2015\**\**\*.png');
% New destination folder
destFolder = 'D:\NewFolder';
%Cell array with file names
FilesName = {};
for k = 1:numel(FilesName)
sourceFile = fullfile(myDir(k).folder, myDir(k).name);
movefile(sourceFile, destFolder);
Name Size Bytes Class Attributes
FilesName 1x5022 1051326 cell
destFolder 1x12 24 char
k 1x1 8 double
myDir 5022x1 4280856 struct
However, when I use... for k = 1:3:numel(FilesName) the code does what I want (move all .png files under folder D:\2015\...
My question is why myDir above is repeating the same file name 3 times? I believe that is because when k=2 cannot find the file as it was already moved. Then, I am obligated to skip every 3 files. Maybe I am using the wildcards in the wrong context here?
Your comments are welcome.
dpb on 26 Feb 2020
Well, that would indicate that's how many files there are in toto, then -- at least with that wildcard pattern.
Have you exhaustively verified you have the subdirectories wanted and only the subdirectories wanted?
I forget who wrote it but at least one of the other regulars here has written examples of recursive subdirectory a search by subject for the phrase. There may also be (and almost certainly is) submissions at the File Exchange.

Sign in to comment.

Accepted Answer

Jyotsna Talluri
Jyotsna Talluri on 28 Feb 2020
Edited: Jyotsna Talluri on 28 Feb 2020
To list all files with a particular extension in all folders and subfolders,you can use dir ( <path> /**/* <extension>) .In your code
myDir = dir('D:\2015\**\**\*.png')
considers each subfolder recursively in the folder D:\2015 and lists files with .png extension in all the folders and subfolders , due to which each file is listed many times. Just use
myDir = dir('D:\2015\**\*.png')
to list all files with .png extension in all folders and subfolders in this path D:\2015
Refer to the link dir for more details

More Answers (0)


Find more on Startup and Shutdown 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!