1

I would like to extract filename from directory in R on Linux Server.

The basename function in R will only work on Windows system. In Python, there is a package called ntpath that could extract filename from directory very easily on Linux environment.

path <- "C:\\Data\\2019\\201907\\20190726\\myfile.txt"
name <- basename(path)

The expected output would be myfile.txt. However, this will only work in Windows system but not Linux server. Basename function on Linux Server will give the full path.

Jian
  • 365
  • 1
  • 6
  • 19
  • ```basename ``` in R uses ```/``` as default separator – LazyCoder Jul 26 '19 at 22:35
  • R recognizes `/` on windows, too, so you can safely use `/` on every system without risk of OS-splintering. If you are not certain which format you're getting, you might be able to safely use `gsub("\\\\", "/", path)` to convert backslash-based paths to forward-slash. (Though I find it curious that on windows, `basename` accepts both, but on linux, it only accepts forward-slash ... \*shrug\*, more reason to only ever use forward-slash.) – r2evans Jul 26 '19 at 22:59

1 Answers1

3

Since R recognizes / as default separator on Linux and \\ as one of the separators on Windows apart from /, you may work around it in the following fashion.

path <- "C:\\Data\\2019\\201907\\20190726\\myfile.txt"
path <- gsub("\\", "/", path, fixed=TRUE)
name <- basename(path)

Happy coding :)

LazyCoder
  • 1,267
  • 5
  • 17