clc
clear all
filePath = uigetdir; % 選擇要處理的子文件夾所在的文件夾 或者直接指定
files = dir(filePath);
oldName = cell(length(files)-2,1);%含有所有子文件夾名字的元胞數組 前兩個無效
for i = 3:length(files)
oldName{i-2} = files(i).name;%把文件夾名字提取出來重新排列
end
newName = cell(length(oldName), 1);%建立新的名字數組
for j = 1:length(oldName)
a = oldName{j}; %獲取之前的名字
b = num2date(a); % 對之前的名字按照規律進行處理 這里是使用num2date函數將日期序列值轉為yymmdd形式
%b = num2str(b, '%08d'); % 如果是1、2...340 這樣的編號 使文件名等長
newName{j} = b; %
movefile([filePath '\' oldName{j}], [filePath '\' newName{j}]) % 更改成功
end
關於num2date函數:
用於將 '2016221'(2016年第221天) 轉換為 '20160729'(2016年7月29日) 形式,這里用於處理MODIS數據時將hdf文件名中的數據日期轉換至正常年月日以便匹配理解
function [ date ] = num2date( code )
% num2date
% 輸入參數是字符格式的序列日期'yyyyddd'
% 輸出值是字符格式的年月日日期'yyyymmdd'
judge=str2num(code(1:4)); %提取出前四位年份
seq=str2num(code(5:7)); %提取出后三位排列天數
A = datetime(judge,01,01); %一年中第一天
B = datetime(judge,12,31); %一年中最后一天
C = linspace(A,B,337+eomday(judge,2)); %創建一年時間序列,eomday得到每年二月份的天數
date=num2str(yyyymmdd(C(seq))); %匹配序列天數對應的年月日,並轉換格式為char類型
% if rem(judge ,4) == 0 && rem(judge ,100) ~= 0 %閏年
% fprintf('%g year is leap year\n',judge)
% elseif rem(judge,400)==0
% fprintf('%g year is leap year\n',judge) %閏年
% else
% fprintf('%g year is ordinary year\n',judge) %平年
% end
end
結果展示:

批量修改某一文件夾下所有文件的名字:
filePath='E:\1SMAPDATA\01COM\01Spr';%文件夾路徑
fileFolder=fullfile(filePath);%
dirOutput=dir(fullfile(fileFolder,'*.tif')); %tif文件
fileNames={dirOutput.name}';
for i = 1:length(fileNames)
a = strsplit(fileNames{i},'_'); %獲取之前的名字
movefile([filePath,'\',fileNames{i}], [filePath,'\',a{5},'.tif']);
end
PS:如果怕出問題,最好把原始數據先備份,以免分辨不出數據。
