How to replace a certain part of file name

5 ビュー (過去 30 日間)
Raja Bilal Rsb
Raja Bilal Rsb 2018 年 7 月 25 日
コメント済み: Raja Bilal Rsb 2018 年 7 月 26 日
I am writing a small code to that goes through the overall directory scans for all files, and if any image file have not same name pattern it will change it.
loc = 'File Directory';
flist = dir([loc '*.png']);
for ii = 1:1:length(flist)
fname = flist(ii).name;
[~, fn, xt] = fileparts(fname);
img = imread([loc fname]);
idxs = strfind(fn, '_');
label = str2double(fn(idxs(end)+1:end));
if label ~= 0
label= 0;
ffname = fullfile(loc, num2str(label), fname); % full file name
imwrite(img, ffname);
continue;
end
My all files have file names like "m_7_13_10" with 10 being constant at the end. I want to change the 10 at end to 0. File should be in the same directory. What I am missing any one?

回答 (1 件)

Guillaume
Guillaume 2018 年 7 月 25 日
編集済み: Guillaume 2018 年 7 月 26 日
Loading the images and saving them back again just to change a filename is a big waste of time. Just rename the files!
An efficient way to do that:
loc = ...
flist = dir(fullfile(loc, '*.png'));
torename = endsWith({flist.name}, '_10.png');
for file = flist(torename)'
movefile(fullfile(loc, file.name), fullfile(loc, regexprep(file.name, '_10\.png', '_0.png', 'preservecase')));
end
  3 件のコメント
Guillaume
Guillaume 2018 年 7 月 26 日
Ok, if you want to load the image and rename them, it's more or less the same:
loc = ...
flist = dir(fullfile(loc, '*.png'));
torename = endsWith({flist.name}, '_10.png');
for file = flist(torename)'
img = imread(fullfile(loc, file.name);
%... further processing
imwrite(img, regexprep(file.name, '_10\.png', '_0.png', 'preservecase'));
end
Raja Bilal Rsb
Raja Bilal Rsb 2018 年 7 月 26 日
The code is still missing the important thing that not every time last part will not be same. it can be _10,_9,_8 from 0 to 10 can be any. It should convert all these to _0, and than convert the file to gray-scale and crop it to 28*28.

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

カテゴリ

Help Center および File ExchangeInstall Products についてさらに検索

製品


リリース

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by