rename files inside the folder

I have to rename files that is placed inside the folder, for e.g. in the below shown example 080 needs to be replaced as 020.. Any help ??
1_ss_ddd_080_y000.txt
1_ss_ddd_080_y001.txt
1_ss_ddd_080_y002.txt

 采纳的回答

Voss
Voss 2022-3-23
编辑:Voss 2022-3-23
old_file_names = { ...
'1_ss_ddd_080_y000.txt', ...
'1_ss_ddd_080_y001.txt', ...
'1_ss_ddd_080_y002.txt'};
new_file_names = strrep(old_file_names,'080','020');
for ii = 1:numel(old_file_names)
movefile(old_file_names{ii},new_file_names{ii});
end

5 个评论

Thanks, actually there are 100 files not just 3 files.. Is there any way to rename all the files in the directory ??
1_ss_ddd_080_y000.txt
1_ss_ddd_080_y001.txt
1_ss_ddd_080_y002.txt
.
.
.
.
1_ss_ddd_080_y100.txt
The loop works the same whether there are 3 or 100 or 100000 files.
However, one thing to consider is whether MATLAB's working directory is the directory where the files are. Because if not, you ned to refer to the files by their full paths. This renames all the .txt files in the directory your_directory:
your_directory = 'C:\path\to\some\folder';
s = dir(fullfile(your_directory,'*.txt'));
old_file_names = fullfile(your_directory,{s.name});
new_file_names = fullfile(your_directory,strrep({s.name},'080','020'));
for ii = 1:numel(old_file_names)
movefile(old_file_names{ii},new_file_names{ii});
end
End up with below error
Error using movefile
Cannot copy or move a file or directory onto itself.
I guess one of the files didn't have '080' in the name (possibly because it was already renamed by a previous run of this code).
To handle that situation, I skip the file in that case:
your_directory = 'C:\path\to\some\folder';
s = dir(fullfile(your_directory,'*.txt'));
old_file_names = fullfile(your_directory,{s.name});
new_file_names = fullfile(your_directory,strrep({s.name},'080','020'));
for ii = 1:numel(old_file_names)
if strcmp(old_file_names{ii},new_file_names{ii})
continue
end
movefile(old_file_names{ii},new_file_names{ii});
end
It's perfect now... Thanks a lot..

请先登录,再进行评论。

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 File Operations 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by