how to remove suffix in lots of folder names
Show older comments
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
Answers (1)
Hari
on 3 Sep 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:
- Refer to the documentation of "dir" for listing directory contents: https://www.mathworks.com/help/matlab/ref/dir.html
- Refer to the documentation of "movefile" for renaming files and directories: https://www.mathworks.com/help/matlab/ref/movefile.html
- Refer to the documentation of "endsWith" for checking string suffixes: https://www.mathworks.com/help/matlab/ref/endswith.html
Hope this helps!
1 Comment
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
Categories
Find more on File Operations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!