9

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?

oguz ismail
  • 1
  • 16
  • 47
  • 69
Maiasaura
  • 32,226
  • 27
  • 104
  • 108

3 Answers3

17

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

f <- "/long/path/to/file"
basename(f)
# [1] "file"
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
2

What about this?

> path <- "/long/path/to/file"
> require(stringr)
> str_extract(path, "[^/]*$")
[1] "file"
EDi
  • 13,160
  • 2
  • 48
  • 57
0

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"
Flo
  • 127
  • 1
  • 1
  • 7