findFiles
findFiles check files in a folder looking for files in which the name
matches a pattern
The pattern can have Metacharacters like:
\w Any alphabetic, numeric, or underscore character.
\d Any numeric digit; equivalent to [0-9]
+ Get characters 1 or more times consecutively.
Examples:
Suppose we have the following files:
Image2.bmp
Image5.bmp
Image_not_pattern.bmp
Image3.bmp
Image7.bmp
other_stuff.bmp
Image1.bmp
Image4.bmp
Image8.bmp
And we want to select only the "images", our pattern shall be written as:
pattern='image(\d+).bmp'
Note that here we have 1 tokens, which gives us the number of the image.
Executing the command:
fileList = findFiles('C:\whatever\...',pattern);
The output (fileList) will be a cell matrix (7 by 2):
Image2.bmp 2
Image5.bmp 5
Image3.bmp 3
Image7.bmp 7
Image1.bmp 1
Image4.bmp 4
Image8.bmp 8
If desired, you can sort it changing 2nd column from char to number and
using the sortrows command:
char2num
for count1=1:1:size(fileList,2)
fileList{count1,2} = str2num(fileList{count1,2});
end
sortrows(fileList, 2)
A more challenging problem is:
Suppose we have the following files:
itrs3_ab_18_4--1.6e-10delay09443.dat
itrs3_ab_18_4--1e-06delay09517.dat
itrs3_ab_18_4--1e-07delay09716.dat
itrs3_ab_18_4-2e-06delay09490.dat
itrs3_ab_18_4-3e-06delay09521.dat
itrs3_ab_18_4--3e-08delay09511.dat
itrs3_ab_18_4-3e-09delay09681.dat
And we want to select only the files that has a 6 before "delay", our
pattern shall be written as:
pattern='itrs3_ab_(\d+)_4-(|-)(\d+)e-06delay(\d+).dat'
Note that here we have 4 tokens:
The 1st, 3rd and 4th are (\d+), they will read the numbers.
The 2nd is (|-), will check if there is nothing or a minus symbol.
Executing the command:
fileList = findFiles('C:\whatever\...',pattern);
The output (fileList) will be a cell matrix (3 by 4):
itrs3_ab_18_4--1e-06delay09517.dat 18 - 1 09517
itrs3_ab_18_4-2e-06delay09490.dat 18 2 09490
itrs3_ab_18_4-3e-06delay09521.dat 18 2 09521
For more information about tokens, see <a href="matlab:
web('http://www.mathworks.com/help/matlab/matlab_prog/regular-expressions.html')">regular-expressions on Matlab</a>.
See also regexp, dir.
Cite As
Carlos Galdino (2024). findFiles (https://www.mathworks.com/matlabcentral/fileexchange/54057-findfiles), MATLAB Central File Exchange. Retrieved .
MATLAB Release Compatibility
Platform Compatibility
Windows macOS LinuxCategories
Tags
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!Discover Live Editor
Create scripts with code, output, and formatted text in a single executable document.
findFiles/
Version | Published | Release Notes | |
---|---|---|---|
1.0.0.0 |
Comments changed.
|