1

I have a list of strings that look like this:

/disk1/home/alb/main/directory1/image0001.png

I want to remove everything after the last / and end up with a string that looks like this:

/disk1/home/alb/main/directory1/

Is there a fast way to do this?

Thank you

1

2 Answers 2

5

You will want to use the first output of fileparts as it is guaranteed to work on all platforms. The fileparts function is a built-in designed to separate a path into it's directory, filename, and file extension.

string = '/disk1/home/alb/main/directory1/image0001.png'
part = fileparts(string);

If you really need that trailing slash (you shouldn't if you use fullfile to (correctly) construct a new path), then you can add it to the end using filesep.

part_with_slash = [part, filesep];

If for some reason you are trying to process this *nix file path on a Windows machine (which has a different file separator), Only then you could use the following regexp.

part = regexp(string, '.*/', 'match');
Sign up to request clarification or add additional context in comments.

3 Comments

Forgot about this function while answering, removed my answer since this is definitely the best solution. +1 for platform independence
Fun fact: fileparts just uses find to locate locations of /, \, and the last .
@excaza And does all of the nice checking to ensure compatibility with UNC paths and cases where you only pass it a filename with no leading directory :)
1

You can use a regex:

str = "/path/to/file.png"

regexprep(str,'([A-Za-z0-9]\.png)?','once')

The ? makes it lazy, this is, the shortest match possible.

1 Comment

thank you, this works really well in the example i gave. My name of directories is a little more complicated, i gave a simpler version to make things simpler. My string looks like this : '/disk1/home/alb/main/directory1/direct1_subdir1_image0001.png' When i use your solution it removes the png but not the whole direct1_subdir1_imag0001. Any ideas how to solve this?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.