フィルターのクリア

how to rename multiple file with sequent custom number?

1 回表示 (過去 30 日間)
adhi dermawan
adhi dermawan 2022 年 11 月 29 日
コメント済み: adhi dermawan 2022 年 12 月 12 日
dear matlab expert, I have a folder contain multiple txt file as following
1.txt
5.txt
9.txt
13.txt
17.txt
21.txt
25.txt
29.txt
33.txt
37.txt
I want to rename these files and add an underline.So my output should look like this:
2015_001.txt
2015_002.txt
2015_003.txt
2015_004.txt
2015_005.txt
2015_006.txt
2015_007.txt
2015_008.txt
2015_009.txt
2015_010.txt
I tried this code but nothing happened
% Directory of the files
d = 'C:\ZTD\pwv2015';
% Retrieve the name of the files only
names = dir(d);
names = {names(~[names.isdir]).name};
% Calculate the length of each name and the max length
len = cellfun('length',names);
mLen = max(len);
% Exclude from renaming the files long as the max
idx = len < mLen;
len = len(idx);
names = names(idx);
% Rename in a LOOP
for n = 1:numel(names)
oldname = [d names{n}];
newname = sprintf('2015_%s%0*s',d,mLen, names{n});
dos(['rename "' oldname '" "' newname '"']); % (1)
end

採用された回答

Rik
Rik 2022 年 11 月 29 日
You may want to consider using movefile instead. That will make this code rely only on Matlab tools, instead of being OS-specific. movefile will also work if you forget to put in the double quotes next time.
The other function you should have been using is fullfile. String concatenation has a habit of making you forget the file separator between folder and file. Your format also does not account for 3 inputs.
oldname = fullfile(d,names{n});
newname = fullfile(d,sprintf('2015_%s%0*s',mLen, names{n}));
  3 件のコメント
Rik
Rik 2022 年 11 月 29 日
Why did you change so much of the existing code and remove almost all comments? Now your code is more difficult to read and understand.
And why are you using movefile(d,newnames{j},'f')? What exactly do you expect to happen with that syntax?
Your previous code almost did the job, it only needed the correction I pointed out.
adhi dermawan
adhi dermawan 2022 年 12 月 12 日
sorry for late reply, already solved it. thanks for your help sir

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeWhos についてさらに検索

タグ

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by