如何仅从路径中提取文件/文件夹名称?

问题描述 投票:0回答:4

不幸的是我对正则表达式很烂。如果我有这样的路径:

/long/path/to/file
,我只需要提取
file

如果有人提供

file/
我只需要
file

如果有人提供

/file/
,我还需要
file

我一直使用

stringr
函数作为拐杖,但这似乎是直接的
grep
领域。请帮忙?

r stringr
4个回答
17
投票

如果我理解正确的话,你可以使用

basename
功能。

f <- "/long/path/to/file"
basename(f)
# [1] "file"

2
投票

这个怎么样?

> path <- "/long/path/to/file"
> require(stringr)
> str_extract(path, "[^/]*$")
[1] "file"

0
投票

很抱歉回答一个非常老的问题,但我被引导到这里寻找一种方法来仅提取完整文件名的directory部分。

这是如何提取目录的:

> f <- "/long/path/to/file"
> dirname(f)
[1] "/long/path/to"

0
投票

当我尝试 dirname(f) 时,我得到了令人惊讶的毫无帮助的返回“。”所以,我尝试了 z <- getwd(), which returned the path to the working directory as a character string, which at least in my current use case is actually useful.

© www.soinside.com 2019 - 2024. All rights reserved.