Get filename without extension in R

There's a built in file_path_sans_ext from the standard install tools package that grabs the file without the extension.

tools::file_path_sans_ext("ABCD.csv")
## [1] "ABCD"

basename will also remove the path leading to the file. And with this regex, any extension will be removed.

filepath <- "d:/Some Dir/ABCD.csv"
sub(pattern = "(.*)\\..*$", replacement = "\\1", basename(filepath))

# [1] "ABCD"

Or, using file_path_sans_ext as Tyler Rinker suggested:

file_path_sans_ext(basename(filepath))

# [1] "ABCD"

You can use sub or substr

sub('\\.csv$', '', str1) 
#[1] "ABCD"

or

substr(str1, 1, nchar(str1)-4)
#[1] "ABCD"

Using the 'file_path' from @JasonV's post

sub('\\..*$', '', basename(filepath))
#[1] "ABCD"

Or

library(stringr)
str_extract(filepath,  perl('(?<=[/])([^/]+)(?=\\.[^.]+)'))
#[1] "ABCD"

data

str1 <- 'ABCD.csv'

Tags:

R

R Faq