how to remove suffix in lots of folder names

4 visualizaciones (últimos 30 días)
vincent lin
vincent lin el 17 de Jul. de 2021
Editada: Stephen23 el 3 de Sept. de 2024
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

Respuestas (1)

Hari
Hari el 3 de Sept. de 2024
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 comentario
Stephen23
Stephen23 el 3 de Sept. de 2024
Editada: Stephen23 el 3 de Sept. de 2024
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

Iniciar sesión para comentar.

Categorías

Más información sobre MATLAB en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by