Extract only folder name right before filename from full path

╄→гoц情女王★ 提交于 2020-01-04 05:59:01

问题


I have the following path

filePath <- "/data/folder1/subfolder1/foo.dat"

I'd like to get subfolder1 which is where foo.dat locates. I saw solutions in other languages but haven't found one in R. What is the simplest way to do it? Thank you!

What I tried

> basename(filePath)
[1] "foo.dat"

> dirname(filePath)
[1] "/data/folder1/subfolder1"

回答1:


This may solve:

filePath <- "/data/folder1/subfolder1/foo.dat"

basename(dirname(filePath))

http://www.r-fiddle.org/#/fiddle?id=IPftVEDk&version=1




回答2:


This may not be the prettiest answer, but it will work for you:

unlist(strsplit(filePath, '/'))[length(unlist(strsplit(filePath, '/')))-1]


来源:https://stackoverflow.com/questions/47189479/extract-only-folder-name-right-before-filename-from-full-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!