Last few characters of a string

22 views (last 30 days)
RoySam
RoySam on 24 Aug 2017
Edited: Stephen23 on 24 Aug 2017
I have directories with filenames that are long string of digits. For example 1.3.6.1.4.1.14519.5.2.1.5168.1900.105097869285462803844775342850 I would like to select my file based on the last four digits of the file ( I manually provide the needed digits to check) So I will code in if last four digits =8250 then Neededfile=1.3.6.1.4.1.14519.5.2.1.5168.1900.105097869285462803844775342850 I got the list but I don't know how to check dd.name for the last four digits? I looked in sscanf, strfind but I could not figure out the appropriate use.
% code
dirarray = dir(datapath); for i=1:numel(dirarray) dd = dirarray(i); HELP NEEDED HERE disp('found file'); end end
Thanks.

Accepted Answer

Jan
Jan on 24 Aug 2017
Edited: Jan on 24 Aug 2017
Either consider the filter at obtaining the files already:
DirList = dir(fullfile(datapath, '*8250'))
Or use FEX: strncmpr (fast, but you need to compile the C code):
DirList = dir(fullfile(datapath, '*'));
NameList = {DirList.name};
Match = NameList(strncmpr(NameList, '8250', 4));
Or use a regular expression:
index = ~cellfun('isempty', regexp(NameList, '8250$'));
Match = NameList(index)
  1 Comment
Stephen23
Stephen23 on 24 Aug 2017
Edited: Stephen23 on 24 Aug 2017
+1 for the neat use of dir in the first method.
Another possibility would be to extract the last four characters:
D = dir(...);
last4 = cellfun(@(s)s(end-3:end),{D.name},'uni',0);
or
last4 = regexp({D.name},'\d{4}$','match')
which can then be easily compared using strcmp, ismember, etc.

Sign in to comment.

More Answers (0)

Categories

Find more on Large Files and Big Data 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!