MATLAB: How to copy a file from one folder to several folders with some change within the text

copyfilefolderMATLABmultiple

Suppose I have this situation,
Master folder > Folder1, Folder2, Folder3…..
Now in Folder1 I have one matlab script named m1.m
I want to copy this m1.m into all other folders with name as m2.m, m3.m….so on and also I want to change some text within the script when it copied into other folder.
How can I do this automatically with some script?
Thanks

Best Answer

This works. Adapt as needed:
% Create vector of folder numbers.
folderNumbers = 1 : 3 % However many you want.
% Specify input folder
inputFolder = pwd; % Or 'folder1', etc.
% Specify what file to copy.
fileNameToCopy = fullfile(inputFolder, 'test.m');
if ~isfile(fileNameToCopy)
errorMessage = sprintf('File does not exist:\n%s', fileNameToCopy);
uiwait(errordlg(errorMessage));
return;
end
% Get the base file name
[f, baseInputFileName, ext] = fileparts(fileNameToCopy)
% File exists, so copy it to folders "Folder 1", "Folder 2", etc.
for k = 1 : length(folderNumbers)
% Create the output folder name.
thisFolder = sprintf('Folder %d', folderNumbers(k));
if ~isfolder(thisFolder)
mkdir(thisFolder);
fprintf('Creating folder %s\n', thisFolder);
end
% Create the output file name.
baseFileName = sprintf('%s %d%s', baseInputFileName, k, ext);
thisOutputFileName = fullfile(thisFolder, baseFileName);
% Now do the copy
copyfile(fileNameToCopy, thisOutputFileName);
fprintf(' Copied file "%s" to folder "%s" as "%s"\n', ...
[baseInputFileName, ext], thisFolder, baseFileName);
end