haskellpathposix

How can I extract the base name of a directory with at least one dot in its name?


Assuming a POSIX path to a specific folder in the macOS filesystem:

/root/Owners/J.F. Kennedy

I would like to obtain J.F. Kennedy.

I used takeFileName function to solve this problem, but I feel there is a better tool for this job.

Is there any function in System.FilePath or System.Directory modules which can accomplish the task at hand ?


Solution

  • As per the comments, it's reasonable to consider any path as consisting of a directory part (every component except the last) and a filename part (the last, possibly empty, component) that can be simultaneously retrieved with splitFileName or individually retrieved with takeDirectory or takeFileName, and it doesn't matter if the path refers to a regular file or a directory.

    Be warned that if you want to take the last non-empty component of the path, you should consider using:

    takeFileName . dropTrailingPathSeparator
    

    instead. This should properly handle all the weird cases of extra path separators:

    "/a/b/c" -> "c"
    "/a/b/c/" -> "c"
    "//a///b//c////" -> "c"
    

    and will only return an empty component if the entire path is empty (or only consists of path separators).