Using wildcards in dir only for strings

조회 수: 7 (최근 30일)
Cl
Cl 2014년 10월 27일
답변: Anand Swaroop 2021년 12월 7일
I have a set of files named
abc1.mat
yhs2.mat
slk3.mat
etc. I need to loop through them all and find the files with the specified number, so my initial thought was to use
dir('*',number,'*')
but this causes a problem when the numbers reach double figures. So if I search for 1, I will get 1, 10, 11, 12 etc. Is there any way of searching for just the number and removing those that I would not want?

답변 (1개)

Anand Swaroop
Anand Swaroop 2021년 12월 7일
To filter out file which has a number supposed to match exactly (not partially).
We can try below code snippet.
% Your search criteria
filelist = dir(['*' num2str(number,'%d') '*']);
% Using regex to match exact number
filename = regexp({filelist.name}, ['[a-zA-Z]+' num2str(number,'%d') '[a-zA-Z.]+'], 'match');
% Removing empty cells
filename(~cellfun('isempty',filename))
When we are using dir(),we cannot do much solely using wild characters. So, we must use some alternate solution. Hope this will solve your problem.
Best Regards,
Anand Swaroop

카테고리

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