grouping files together by name

8 views (last 30 days)
MJ
MJ on 11 Aug 2021
Commented: MJ on 11 Aug 2021
I would like to iterate through a list of PNG files in a folder (inputdir) and group them based on their file name.
The png filenames end in a format like xxx.01.001.png, xxx.01.002.png... xxx.01.256.png, where xxx is irrelevant.
and I would like to group and move the 256 png files into one folder in a directory like inputdir/01
And repeat the same for other groups like xxx.02.001.png, xxx.03.001.png and so forth
How would this be accomplished? I am trying to code the solution but I am stuck.
cd inputdir
S = dir(fullfile(inputdir,'*.PNG'));
for k = 1:numel(S)
fnm = fullfile(inputdir,S(k).name);
newj = % some code here
if j ~= newj
mkdir(string(newj));
j = newj;
end
end

Accepted Answer

Image Analyst
Image Analyst on 11 Aug 2021
You'll need to parse the filenames then sort them by whatever number you want to sort them by. You can use fileparts() and strsplit() to break the filename into parts. Here is a start:
S = dir(fullfile(inputdir,'*.PNG'))
allFileNames = {S.name};
for k = 1 : length(allFileNames)
thisName = allFileNames{k};
[~, baseFileNameNoExt, ext] = fileparts(thisName);
if ~contains(baseFileNameNoExt, '.')
continue; % Skip names with no dot in them.
end
fprintf('Processing %s.\n', baseFileNameNoExt);
nameParts = strsplit(baseFileNameNoExt, '.')
end

More Answers (1)

Simon Chan
Simon Chan on 11 Aug 2021
Following code assumes all your png files are inside the working directory and the filename format are xxxx.00.000.png.
clear; clc;
myFolder = 'C:\Users'; % Your working directory
S = dir(fullfile(myFolder,'*.png'));
filename = {S.name};
filename_split = cellfun(@(x) strsplit(x,'.'),filename,'UniformOutput',false);
filename_combine = vertcat(filename_split{:});
foldername = unique(filename_combine(:,2));
cellfun(@(x) mkdir(fullfile(myFolder,x)),foldername);
cellfun(@(x,y) movefile(fullfile(myFolder,x),fullfile(myFolder,y)),filename,filename_combine(:,2)');

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!