Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the last 2 directories of a file path

I have a file path of, for example /Users/Documents/New York/SoHo/abc.doc. Now I need to just retrieve /SoHo/abc.doc from this path.

I have gone through the following:

  • stringByDeletingPathExtension -> used to delete the extension from the path.
  • stringByDeletingLastPathComponent -> to delete the last part in the part.

However I didn't find any method to delete the first part and keep the last two parts of a path.

like image 522
james lobo Avatar asked Nov 10 '11 12:11

james lobo


People also ask

What is the last part of a file path called?

Extension or Filename Extension or File Extension: I like the last one.

How do I get the last part of a path in Python?

Use os. path. basename() to extract the last folder or the file from a path.

How do I get the last directory name in Unix?

How do I get directory name from its path on a Linux or Unix-like system? [/donotprint]In other words, you can extract the directory name using dirname command.


1 Answers

NSString has loads of path handling methods which it would be a shame not to use...

NSString* filePath = // something

NSArray* pathComponents = [filePath pathComponents];

if ([pathComponents count] > 2) {
   NSArray* lastTwoArray = [pathComponents subarrayWithRange:NSMakeRange([pathComponents count]-2,2)];
   NSString* lastTwoPath = [NSString pathWithComponents:lastTwoArray];
}
like image 126
jbat100 Avatar answered Oct 04 '22 21:10

jbat100