grouping files together by name

10 次查看(过去 30 天)
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

采纳的回答

Image Analyst
Image Analyst 2021-8-11
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

更多回答(1 个)

Simon Chan
Simon Chan 2021-8-11
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)');

类别

Help CenterFile Exchange 中查找有关 File Operations 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by