MATLAB Answers

S Roy
0

How to separate a portion of filename from a file

Asked by S Roy
on 8 Sep 2019
Latest activity Answered by madhan ravi
on 8 Sep 2019
How to separate a portion of filename from a file like I have the file 'scrubbed.MOD_D3_AOD_550.20020112.nc' I just want to extract the '20020112' part

  0 Comments

Sign in to comment.

Tags

4 Answers

Answer by Adam Danz
on 8 Sep 2019
Edited by Adam Danz
on 8 Sep 2019
 Accepted Answer

[~, fname] = fileparts('scrubbed.MOD_D3_AOD_550.20020112.nc');
[~,tok] = regexp(fname,'.(\d+)$','match','tokens');
str = tok{1}{1};

  4 Comments

Show 1 older comment
fileparts() just splits up the path into parts. You can read more here:
regexp() uses regular expressions to find patterns in a string. The "$" symbol indicates that the pattern must be at the end of the string. The pattern should start with a decimal point followed by at least 1 number. The parentheses define a "token" that is returned in 'tok'.
Thanks It really helped.
Glad I could help. The other answers here reminded me to make clear the assumption in my answer that the string of interest is always at the end of the filename (ignoring the final file extension) and is preceeded by a decimal point.

Sign in to comment.


Answer by Stephen Cobeldick on 8 Sep 2019

Simpler:
>> str = 'scrubbed.MOD_D3_AOD_550.20020112.nc';
>> out = regexp(str,'\d{8}','match','once')
out = 20020112

  2 Comments

Thanks it works fine
It is simpler and assumes that the string of interest will always have 8 digits and that will be the only sub-string with 8 digits.

Sign in to comment.


Answer by Image Analyst
on 8 Sep 2019

Try strsplit():
parts = strsplit('scrubbed.MOD_D3_AOD_550.20020112.nc', '.') % Separate in between dots.
yourNumber = parts{end-1} % Take the next to the last one.

  2 Comments

This is also simpler than my answer if the assumptions are true that the string of interest is the 2nd to last segment surrounded by decimal points.
Thanks. Now I know many different ways to do it.

Sign in to comment.


Answer by madhan ravi
on 8 Sep 2019

regexp('scrubbed.MOD_D3_AOD_550.20020112.nc',...
'\d*(?=\.nc)','match','once')

  0 Comments

Sign in to comment.