필터 지우기
필터 지우기

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 CenterFile Exchange에서 Whos에 대해 자세히 알아보기

태그

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by