how to remove suffix in lots of folder names

4 次查看(过去 30 天)
I have lots of folders with name
a_local
b_local
c_local
How to change or remove all the _local to make the folder name
a
b
c

回答(1 个)

Hari
Hari 2024-9-3
Hi Vincent,
I understand that you want to rename multiple folders by removing the "_local" suffix from each folder's name.
I assume you have access to the directory containing these folders and that you want to perform this operation programmatically using MATLAB.
  • List All Folders: Use the dir function to list all items in the directory. Filter out files and keep only directories that have the "_local" suffix.
  • Loop Through Each Folder: Iterate over each folder that needs renaming. Extract the base name by removing the "_local" suffix.
  • Rename Folders: Use the movefile function to rename the folders. This function can change folder names by moving them to a new name.
  • Error Handling: Include error handling to manage potential issues, such as name conflicts or permission errors.
  • Verify Changes: After renaming, you might want to verify that all folders have been renamed correctly by listing the directory contents again.
Please find the complete code for the same:
% Get list of all items in the current directory
items = dir();
% Filter out folders that end with '_local'
folders = items([items.isdir] & endsWith({items.name}, '_local'));
% Loop through each folder
for i = 1:length(folders)
oldName = folders(i).name;
% Remove '_local' suffix
newName = extractBefore(oldName, '_local');
try
% Rename the folder
movefile(oldName, newName);
catch ME
fprintf('Error renaming folder %s: %s\n', oldName, ME.message);
end
end
% Verify changes
updatedItems = dir();
disp({updatedItems.name});
References:
Hope this helps!
  1 个评论
Stephen23
Stephen23 2024-9-3
编辑:Stephen23 2024-9-3
Using DIR more effectively, to reduce the possible number of items returned:
P = 'absolute or relative path to where the folders are';
S = dir(fullfile(P,'*_local'));
S(~[S.isdir]) = [];
for k = 1:numel(S)
old = S(k).name;
new = strrep(old,'_local','');
[status,msg] = movefile(...
fullfile(S(k).folder,old),...
fullfile(S(k).folder,new));
if ~status
fprintf('%s\n',msg)
end
end

请先登录,再进行评论。

类别

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

Community Treasure Hunt

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

Start Hunting!

Translated by