making multiple copies of a file

I would like to make multiple copies of a file each of which will have a different name. example: source file: A.txt copies A1.txt, A2.txt... How can I use copyfile and be able to do this? Thanks for inputs

 採用された回答

Walter Roberson
Walter Roberson 2011 年 9 月 1 日

2 投票

copyfile() can only create one copy at a time, so you will need a loop (whether explicit or implicit)
One of numerous possible ways:
sourcefile = 'A.txt';
numcopies = 20;
[path, basename, ext] = fileparts(sourcefile);
filepattern = fullfile(path, [basename '%d.' ext]);
destnames = cellstr(num2str((1:numcopies).', filepattern);
cellfun(@(FID) copyfile(sourcefile, FID), destnames);

4 件のコメント

Ram
Ram 2011 年 9 月 1 日
Thanks for your input. Is there a way to break up the basename so that I can have the destinations filenames as A11.txt, A21.txt, A31.txt ...
Walter Roberson
Walter Roberson 2011 年 9 月 1 日
If those are intended to be consecutive names, then you could change the '%d.' to '%d1.'
Ah, bug fix: the '%d.' should be '%d' or '%d1' (according to your taste); I see from testing that the ext variable will already include the '.' .
Ram
Ram 2011 年 9 月 1 日
I have an error that they are too namy input arguments in the use of the function cellstr. Do you know what might be causing it.
thanks
Walter Roberson
Walter Roberson 2011 年 9 月 1 日
Looks like I left off a close bracket:
destnames = cellstr(num2str((1:numcopies).', filepattern));

サインインしてコメントする。

その他の回答 (3 件)

Amith
Amith 2012 年 12 月 26 日

0 投票

will this work
copyfile('output2.txt',destnames(i));

1 件のコメント

Walter Roberson
Walter Roberson 2012 年 12 月 26 日
No, destnames here is a cell array of strings, so destnames(i) would be a 1 x 1 cellarray, rather than a string. If you used destnames{i} then that would be a string.
You would need to loop "i" over all of the output string possibilities. The cellfun() that I show is responsible for that.

サインインしてコメントする。

Diana Krupnik
Diana Krupnik 2019 年 1 月 28 日

0 投票

This solution names the files by numbering them, would it be possible to instead change the names based on a table that contains string or text?
Sam Apoola
Sam Apoola 2019 年 2 月 14 日

0 投票

This worked for me
% loop for creating 100 copies
n=100;
for i=1:n
jobname{i}= ['copy', num2str(i),'.txt'];
copyfile('original.txt',jobname{i});
end

カテゴリ

ヘルプ センター および File ExchangeCharacters and Strings についてさらに検索

タグ

質問済み:

Ram
2011 年 9 月 1 日

回答済み:

2019 年 2 月 14 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by