How to get the name of the parent folder of a file specified by its full path?

In Matlab, I have a line containing the file path:

path = 'C:/Data/Matlab/Dir/file.m' 

Now I want to extract part of the string < Dir . One way to do this:

 [first, second, third, fourth, fifth] = strtok(path, '/') 

And then take the fourth element and finally remove the first character ( / ) from it.

I'm just wondering if there is a more elegant solution? It seems a bit cumbersome to explicitly store all the elements first ... fifth , and then manually remove / .

Thanks.

+6
source share
7 answers

Try:

 parts = strsplit(path, '/'); DirPart = parts{end-1}; 
+3
source

Try

 s = regexp(path, '/', 'split') s(4) 

as described here in the "Split a line on a delimiter using a broken keyword" section.

+4
source

you can try the fileparts function as follows:

 [ParentFolderPath] = fileparts('C:/Data/Matlab/Dir/file.m'); [~, ParentFolderName] = fileparts(ParentFolderPath) ; ParentFolderName = 'Dir' 
+3
source

find the parent directory with one line of code if you don't know how many folders are in the hierarchy

fliplr (strtok (fliplr (PNAME), '\'))

+2
source

If you do not want to care about the number of elements in your path, and you do not want to use strsplit , which is not available in older versions of Matlab, you can also use this one liner:

 directory = getfield( fliplr(regexp(fileparts(path),'/','split')), {1} ) %% or: % alldir = regexp(fileparts(path),'/','split') % directory = alldir(end) 

which will always return the parent folder of the specified file.

You should also consider using filesep instead of '/' for better compatibility with various systems.

+1
source

there is a good old way ...

 n=size(path,2); while path(n)~='/'; n=n-1; end i=n-2; while path(i)~='/'; i=i-1; end % result path(i+1:n-1) 
0
source

The maximum solution is good for Windows, but may fail on linux / mac due to the slash at the beginning of absolute paths. My suggestion would be:

 parts = strsplit(path, filesep); DirPart = parts{end-1}; if path(1) == filesep DirPart = [filesep,DirPart]; end if path(end) == filesep DirPart = [DirPart,filesep]; end 
0
source

All Articles