How to separate a portion of filename from a file

11 vues (au cours des 30 derniers jours)
S Roy
S Roy le 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

Réponse acceptée

Adam Danz
Adam Danz le 8 Sep 2019
Modifié(e) : Adam Danz le 8 Sep 2019
[~, fname] = fileparts('scrubbed.MOD_D3_AOD_550.20020112.nc');
[~,tok] = regexp(fname,'.(\d+)$','match','tokens');
str = tok{1}{1};
  4 commentaires
S Roy
S Roy le 8 Sep 2019
Thanks It really helped.
Adam Danz
Adam Danz le 8 Sep 2019
Modifié(e) : Adam Danz le 8 Sep 2019
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.

Connectez-vous pour commenter.

Plus de réponses (3)

Stephen23
Stephen23 le 8 Sep 2019
Simpler:
>> str = 'scrubbed.MOD_D3_AOD_550.20020112.nc';
>> out = regexp(str,'\d{8}','match','once')
out = 20020112
  2 commentaires
S Roy
S Roy le 8 Sep 2019
Thanks it works fine
Adam Danz
Adam Danz le 8 Sep 2019
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.

Connectez-vous pour commenter.


Image Analyst
Image Analyst le 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 commentaires
Adam Danz
Adam Danz le 8 Sep 2019
Modifié(e) : Adam Danz le 8 Sep 2019
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.
S Roy
S Roy le 8 Sep 2019
Thanks. Now I know many different ways to do it.

Connectez-vous pour commenter.


madhan ravi
madhan ravi le 8 Sep 2019
regexp('scrubbed.MOD_D3_AOD_550.20020112.nc',...
'\d*(?=\.nc)','match','once')

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by