Match folder names with file names and rename the folder
1 回表示 (過去 30 日間)
古いコメントを表示
I have a path folder names as follows:
~/directory/2000/land/cities/Muscat/
~/directory/2000/land/cities/Riyadh/
..... 1000 fodler names
and a file names in a separate directory as
~/dir/2000/cities/453_Muscat/
~/dir/2000/cities/12_Riyadh/
I want to rename the foldername by matching the name of the files., eg,
the folder names desired are
~/directory/2000/land/cities/453_Muscat/
~/directory/2000/land/cities/12_Riyadh/
..... 1000 fodler names
Any help is much appreciated
0 件のコメント
回答 (1 件)
Deepak
2024 年 8 月 7 日
Hi SChow,
To my understanding, you have over 1000 folders named on different cities in a directory. You also have files named as “number_cityname”, and you want to rename the folders to match the filenames, i.e., “number_cityname”, if a matching file exists.
To do this task, we can write a MATLAB script that will extract all the file names and folder names and store them in different variables.
Then we can create a file map, that will map all the folder names with their corresponding file names.
Finally, we can iterate on all the folder names to rename them based on their respective mapped values by using “movefile” function of MATLAB.
Here is the MATLAB script that addresses the task –
% Define the paths
folderPath = '~/directory/2000/land/cities/';
filePath = '~/dir/2000/cities/';
% Get a list of all folders in the folderPath
folders = dir(folderPath);
folders = folders([folders.isdir]); % Filter out only directories
folders = folders(~ismember({folders.name}, {'.', '..'})); % Remove '.' and '..'
% Get a list of all files in the filePath
files = dir(fullfile(filePath, '*'));
files = files(~[files.isdir]); % Filter out directories
% Create a map to match city names to their new names
fileMap = containers.Map();
for i = 1:length(files)
[~, fileName, ~] = fileparts(files(i).name);
% Extract the city name from the file name
cityName = regexp(fileName, '_', 'split');
cityName = cityName{2};
fileMap(cityName) = fileName;
end
% Rename folders
for i = 1:length(folders)
oldFolderName = folders(i).name;
if isKey(fileMap, oldFolderName)
newFolderName = fileMap(oldFolderName);
oldFolderPath = fullfile(folderPath, oldFolderName);
newFolderPath = fullfile(folderPath, newFolderName);
movefile(oldFolderPath, newFolderPath);
fprintf('Renamed folder %s to %s\n', oldFolderPath, newFolderPath);
else
fprintf('No matching file found for folder %s\n', oldFolderName);
end
end
Attaching the documentation of functions used in the MATLAB script for reference –
I hope this resolves your issue.
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Whos についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!