How to get the path part of a filename?

2019-06-21 18:37发布

问题:

I want to get the path part of a file name in MATLAB like dirname and basename in Linux. I've tried to turn to find a function like strrchr, but I failed. I know strtok, strfind and textscan can be used, but I want to accomplish this with not more than two statements.

回答1:

For this particular problem I suggest you use the fileparts function:

[path, filename, extention] = fileparts(str)


回答2:

Nick's answer definitely does what you ask for, but here's an alternative answer using regexprep:

regexprep(str, '(.+)(?:\\|/)(.*)', '$1')

If you'd want to capture the filename (extension included), use the $2 token instead of $1. It's a good exercise for regular expressions, which prove to be very useful in MATLAB when parsing text.