how to remove suffix in lots of folder names

4 ビュー (過去 30 日間)
vincent lin
vincent lin 2021 年 7 月 17 日
編集済み: Stephen23 2024 年 9 月 3 日
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 Center および File ExchangeMATLAB についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by