Maiasaura
Maiasaura

Reputation: 32996

How do I extract a file/folder_name only from a path?

Unfortunately I suck at regexp. If I have a path like so:

/long/path/to/file, I just need to extact file.

If someone supplies file/ I just need file.

If someone supplies /file/, I still need just file.

I've been using stringr functions as a crutch but this seems like straight up grep territory. Help, please?

Upvotes: 10

Views: 1279

Answers (4)

Lynn
Lynn

Reputation: 1

When I tried:

dirname(f)

I got the stunningly unhelpful return of "." So, I tried:

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.

Upvotes: 0

Flo
Flo

Reputation: 167

Sorry for giving an answer to a very old question, but I was led here searching for a way to extract only the directory part of a full filename.

So here is, how you extract the directory:

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

Upvotes: 0

Joshua Ulrich
Joshua Ulrich

Reputation: 176718

If I understand correctly, you could use the basename function.

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

Upvotes: 18

EDi
EDi

Reputation: 13310

What about this?

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

Upvotes: 2

Related Questions