Rename files: keep only first 5 characters

6 ビュー (過去 30 日間)
ABCDEFG HIJKLMN
ABCDEFG HIJKLMN 2022 年 3 月 14 日
編集済み: Jan 2022 年 3 月 14 日
I have a folder with 250 pictures which I want to rename. The original names are "00XXX.[random numbers]" (with XXX from 001 to 250) and I would like them to simply be named "00XXX", deleting the remaining characters.
Is there an easy way of doing this in a for loop?
Thanks in advance!

採用された回答

Voss
Voss 2022 年 3 月 14 日
編集済み: Voss 2022 年 3 月 14 日
You can use movefile() to rename files. Try something like this on a copy of your folder:
pn = 'path\to\your\directory\';
f = dir(fullfile(pn,'*.png')); % get info about all .png files in folder pn, for instance
for ii = 1:numel(f)
[~,name,ext] = fileparts(f(ii).name);
movefile(fullfile(pn,f(ii).name),fullfile(pn,[name(1:5) ext]));
end
  2 件のコメント
ABCDEFG HIJKLMN
ABCDEFG HIJKLMN 2022 年 3 月 14 日
This worked perfectly, thank you for the help!
Voss
Voss 2022 年 3 月 14 日
You're welcome! Glad it worked

サインインしてコメントする。

その他の回答 (1 件)

Jan
Jan 2022 年 3 月 14 日
編集済み: Jan 2022 年 3 月 14 日
Folder = 'C:\Your\Folder';
List = dir(fullfile(Folder, '*.*'));
List([List.isdir]) = []; % [EDITED] remove folders
for k = 1:numel(List)
Name = List(k).name;
Source = fullfile(Folder, Name);
Dest = fullfile(Folder, strtok(Name, '.'));
[Succ, Msg] = movefile(Source, Dest, 'f');
if Succ == 0
error(Msg);
end
end
  2 件のコメント
ABCDEFG HIJKLMN
ABCDEFG HIJKLMN 2022 年 3 月 14 日
編集済み: ABCDEFG HIJKLMN 2022 年 3 月 14 日
Thank you for your answer. Unfortunetely, it doesn't seem to work. I get the following error: Cannot copy or move a file or directory onto itself.
Jan
Jan 2022 年 3 月 14 日
Then some of the files in this folder do not match the naming scheme "00XXX.[random numbers]". Maybe "." and ".." are the problem. I've updated the code, but if the other answer is working, stay at it.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeStartup and Shutdown についてさらに検索

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by