2

I'm reading multiple .txt files using list.file() and file.path(). Just wanted to parse the full path names and extract the portion after the last “/” and before the “.”

Here is the structure of file path names :

"C:/Users/Alexandre/Desktop/COURS/FORMATIONS/THESE/PROJET/RESULTATS/Vessel features/Fusion/OK/SAT-DPL192C.txt"

The code I've tried

# l <- list.files(pattern = "SAT(.+)*.txt")
# f <- file.path(getwd(), c=(l))
f <- c("C:/Users/Alexandre/Desktop/COURS/FORMATIONS/THESE/PROJET/RESULTATS/Vessel features/Fusion/OK/SAT-DPL192C.txt", "C:/Users/Alexandre/Desktop/COURS/FORMATIONS/THESE/PROJET/RESULTATS/Vessel features/Fusion/OK/SAT-DPL193D.txt")
d <- lapply(f, read.delim)
names(d) <- gsub(".*/(.*)..*", "1", f)

Last string give [1] "1" "1" instead of [1] "DPL192C" "DPL193D" etc...

I've also tried the syntax like ".*/(.+)*..* for the portion to conserv with same result.

1
  • How about gsub(".*([^/]+)\\..*","\\1",f) Commented Jan 7, 2019 at 22:34

1 Answer 1

2

A . is a special character, so you need to escape it. Please, when you want to grab the captured expression, you need to use \\1, not just 1. Try this:

gsub(".*/(.*)\\..*", "\\1", f)
# [1] "SAT-DPL192C" "SAT-DPL193D"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.