how to change a filename

29 次查看(过去 30 天)
Pritha Pande
Pritha Pande 2017-5-23
What command should i give to change file names in one go; as of now i am giving
mypath='C:\Users\Pritha\Desktop\matalb\1996bc\g4.timeAvgMap.M2TMNXAER_5_12_4_BCEXTTAU.199';
names=dir(mypath);
fileNames = {names(~[names.isdir]).name};
for iFile = 1:(fileNames) %# Loop over the file names
newName = sprintf('%d.nc',iFile); %# Make the new name
f=['C:\Users\Pritha\Desktop\matalb\1996bc\g4.timeAvgMap.M2TMNXAER_5_12_4_BCEXTTAU.199',num2str(newName)];
g=['C:\Users\Pritha\Desktop\matalb\1996bc\g4.timeAvgMap.M2TMNXAER_5_12_4_BCEXTTAU.199',num2str(fileNames{iFile})];
movefile(g,f); %# Rename the file
end
g4.timeAvgMap.M2TMNXAER_5_12_4_BCEXTTAU.19960101-19960130.180W_90S_180E_90N.nc
g4.timeAvgMap.M2TMNXAER_5_12_4_BCEXTTAU.19960201-19960231.180W_90S_180E_90N.nc
g4.timeAvgMap.M2TMNXAER_5_12_4_BCEXTTAU.19960301-19960331.180W_90S_180E_90N.nc
g4.timeAvgMap.M2TMNXAER_5_12_4_BCEXTTAU.19960401-19960431.180W_90S_180E_90N.nc
I want them to be name as 1.nc, 2.nc, 3.nc, 4.nc.
  2 个评论
Rik
Rik 2017-5-23
Have you tried googling it? I don't think I'm exaggerating if I say there are hundreds of examples to be found to do this.
One hint: if you are planning on using anything to process your data for which it is useful to keep the original order, use padding. You can do that with sprintf('%04d',n).
Pritha Pande
Pritha Pande 2017-5-24
Ya I know there are. But, I have been trying it for quite long and not able to get the desired result. I wanted to know what is wrong wih my command so, thought of asking it overhere. Anyways,I will try it again with the hint you have given.

请先登录,再进行评论。

回答(1 个)

Walter Roberson
Walter Roberson 2017-5-24
You are missing the directory separator between the folder name and the file name.
I recommend that you re-code using fullfile()
mypath = 'C:\Users\Pritha\Desktop\matalb\1996bc\g4.timeAvgMap.M2TMNXAER_5_12_4_BCEXTTAU.199';
names = dir(mypath);
names([names.isdir]) = [];
fileNames = {names.name};
for iFile = 1: length(fileNames) %# Loop over the file names
newName = sprintf('%04d.nc', iFile); %# Make the new name
f = fullfile(mypath, newName);
g = fullfile(mypath, fileNames{iFile});
movefile(g,f); %# Rename the file
end

类别

Help CenterFile Exchange 中查找有关 Install Products 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by