Sorting Files into subfolders based on name

3 views (last 30 days)
Jason Silver
Jason Silver on 24 May 2019
Answered: Arjun on 9 Aug 2024
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.

Answers (1)

Arjun
Arjun on 9 Aug 2024
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!

Categories

Find more on Shifting and Sorting Matrices 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!