How do I open files whose name matches a string from another file name?

I have two groups of files that all contain a timestamp in their names. The timestamps are identical between file groups. I want to match the files from Group 1 with their counterpart in Group 2, but there are more files in Group 1 than in Group 2. How do I only open files from Group 1 that match a timestamp in Group 2? The timestamp is only part of the filename.
Ex. CAL_LID_2011-11-01T00-47-43ZN.nc
The '2011-11-01T00-47-43' is the timestamp that needs to be matched to a file in Group 2. I've tried to write an if statement to open the files, but I'm stuck. Any help is appreciated! Thanks!

 Accepted Answer

Assuming timestamps are all of the same form, you can find them with regexp:
%filesgroup1: a cell array of string representing file names from group 1
tstamps1 = regexp(filesgroup1, '\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}', 'match', 'once');
You can do the exact same thing for group 2:
filesgroup2: a cell array of string representing file names from group 2
tstamps2 = regexp(filesgroup1, '\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}', 'match', 'once');
You can then check which timestamps from group 2 are in group 1 with ismember:
isingroup1 = ismember(tstamps2, tstamps1);
Finally, you use the logical array returned by ismember to filter your group2 filenames:
files2match1 = filesgroup2(isingroup1);
Note: the regexp matches 4 digits, followed by '-', followed by 2 digits, followed by '-', followed by 2 digits, followed by 'T', followed by 2 digits, followed by '-', followed by 2 digits, followed by '-', followed by 2 digits.

More Answers (1)

Extract the timestamps from the file names with indexing (if the positions are fixed) or strsplit() (if you get lucky with the delimiters) or regexprep (powerful tool but can be difficult to understand)
Once you have the timestamps, you can use ismember() with two outputs to match between the two subsets.
[tf, idx] = ismember(first_timestamps, second_timestamps);
useful_first_files = first_filenames(tf);
matching_second_files = second_filenames(idx(tf));

Categories

Asked:

on 21 Apr 2016

Answered:

on 21 Apr 2016

Community Treasure Hunt

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

Start Hunting!