Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emacs lisp: Get directory name (not path) from the path

I am looking for a simple and portable way of obtaining the last component of the directory path or the directory itself from the path. The semantics of the function should be something like this:

(get-dirname-nonpath "/some/dir/")  ;; should return "dir"
(get-dirname-nonpath "C:\Windows\Path") ;; should return "Path"
(get-dirname-nonpath "/some/path/to/my/source.ext")  ;; returns "my"

In the last example it is also fine if the function returns "source.ext" instead of "my", especially if that would make it shorter. Looking at the emacs, I am unable to find a built-in function that would help in achieving this:

Of course, I could do some string manipulation with (back)slashes, but that looks messy and more like a hack. What is the right way to do it in a robust (OS-oblivious) manner?

EDIT: The best I could find so far is: (file-name-nondirectory (directory-file-name ...))

like image 361
eold Avatar asked Dec 04 '14 01:12

eold


1 Answers

(file-name-nondirectory (directory-file-name (file-name-directory ...)))

You need the last part, if you want your third example to work:

(file-name-nondirectory
   (directory-file-name
     (file-name-directory "/some/path/to/my/source.ext")))

returns "my".

like image 139
Drew Avatar answered Oct 20 '22 09:10

Drew