2

This should be dead simple, but I can't figure it out. I have a string that represents a path name to a file, ie

"C:/blah/this/whatever/filename"

And I need to extract the filename (programatically). I am trying to use strsplit (or str_split) and, it is easy enough to split the string by '/' but.. I cannot fathom how to actually extract one of the values in the returned vector, or determine how many elements are even in the vector (as that may very for my application). Using length (oddly enough, to my mind) does not help. Help?

2 Answers2

7

Taken from: Find file name from full file path

basename("C:/some_dir/a")
> [1]  "a"

dirname("C:/some_dir/a")
>[1] "C:/some_dir"

Although I think the above approach is much better, you can also use the str_split approach - which I really only mention to show how to select the last elements from a list using lapply.

example <- c("C:/some_dir/a","C:/some_dir/sdfs/a","C:/some_dir/asdf/asdf/a")
example.split <- strsplit(example,"/")
files <- unlist(lapply(example.split, tail , 1 ))
Community
  • 1
  • 1
dayne
  • 7,504
  • 6
  • 38
  • 56
  • Thanks!!! For reasons I won't go into, I cannot use the first approach (should have mentioned that I tried it), but the lapply approach does work for my application. Thank you, dayne. –  Sep 25 '13 at 15:03
4

Don't need str_split:

sub( "^.+/(.+)$", "\\1",  "C:/blah/this/whatever/filename" )
eddi
  • 49,088
  • 6
  • 104
  • 155
Ari B. Friedman
  • 71,271
  • 35
  • 175
  • 235