temor
temor

Reputation: 1029

How to extract part of a file name to a text file?

I have several files in a directory data.

these files are named like this:

  file_file_sd_daf_800_800_log-(3-got)_20100101_20121012

All files share all parts of the name but differ with part sd.

I want to extract only this part of file name as one column and write out to text file .

I list all file like this:

   dir<- list.files("C:\\data", "*.txt", full.names = TRUE)

Upvotes: 0

Views: 719

Answers (1)

stas g
stas g

Reputation: 1513

okay, this should work (using regular expressions):

dir_ <- list.files("C:\\data", "*.txt", full.names = TRUE)

tmp <- regmatches(dir_, regexec("file_file_(.+)_daf.+", dir_))
sapply(tmp, "[", 2)

a little test with your example:

x <- "file_file_sd_daf_800_800_log-(3-got)_20100101_20121012"
regmatches(x, regexec("file_file_(.+)_daf.+", x))[[1]][2]

# [1] "sd"

you can then write the different bits you get to a file by using write.

Upvotes: 1

Related Questions