Sorting Files into subfolders based on name

조회 수: 1 (최근 30일)
Jason Silver
Jason Silver 2019년 5월 24일
답변: Arjun 2024년 8월 9일
I have about 10,000 images that I need to sort based on the file name into new folders. Each file is has a nomeclature of F01W01T01Z1.tiff, which each number increases in value. I want to sort each file into a new folder based on unique F value and W values.

답변 (1개)

Arjun
Arjun 2024년 8월 9일
Hi,
As per my understanding, you want to organize your files into folder structure according to the values of F and W in the naming format. This can be done using some file manipulation in MATLAB. Following are the steps to be followed:
  • Define the source directory where your images are stored
  • Get a list of all .tiff files in the source directory
  • Loop through each file, get the full file name, extract the F and W values from the file name using regular expression
  • Check if the file name matches the expected pattern, extract the F and W values, create the new folder path based on F and W values, create the new directories if they do not already exist
  • Move the file to the new directory
Following is the code to achieve the same:
% Define the source directory where your images are stored
sourceDir = 'path/to/your/source/directory';
% Get a list of all .tiff files in the source directory
fileList = dir(fullfile(sourceDir, '*.tiff'));
% Loop through each file
for k = 1:length(fileList)
% Get the full file name
fileName = fileList(k).name;
% Extract the F and W values from the file name using regular expressions
tokens = regexp(fileName, 'F(\d+)W(\d+)T\d+Z\d+', 'tokens');
% Check if the file name matches the expected pattern
if ~isempty(tokens)
% Extract the F and W values
FValue = tokens{1}{1};
WValue = tokens{1}{2};
% Create the new folder path based on F and W values
newFolderPath = fullfile(sourceDir, ['F', FValue], ['W', WValue]);
% Create the new directories if they do not already exist
if ~exist(newFolderPath, 'dir')
mkdir(newFolderPath);
end
% Move the file to the new directory
movefile(fullfile(sourceDir, fileName), fullfile(newFolderPath, fileName));
else
warning('File name %s does not match the expected pattern.', fileName);
end
end
You may need to have a look at Regular Expression in MATLAB(link attached):
I hope this will help!

카테고리

Help CenterFile Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by