[R] extract file name from a path string

Luigi Marongiu marongiu.luigi at gmail.com
Thu Feb 26 17:58:35 CET 2015


Dear all,
what code should I write in order to extract the file name from a give
path? Let's say that I want to get the file "my file.xls" which is in
the directory/folder "My documents"; since I work both with Windows
and Linux, the paths I am looking at are in the format:

path.windows<-"\\home$\\lm667\\My Documents\\my file.xls"
path.linux<-"/home/My Documents/my file.xls"

I used two words for the file name because sometimes the file names
have multiple words rather than a single one separated by capitals,
"." or "_".
The code should now get the file name, which is included between "\\"
(or "/") and ".xls" but I don't know what regular expression will do
the trick.
Once the file name has been assigned to a vector, it should be easy to
remove it from the path.windows/.linux and obtain a vector with the
path on its own.
Essentially the output should be as follows:

> file.name
[1] "my file.xls"
> path.w
[1] "\\home$\\lm667\\My Documents\\"
> path.l
[1] "/home/My Documents/"

Thank you,
Luigi



More information about the R-help mailing list