根据 R 中的父目录复制和重命名特定文件

Copy and rename Specific Files based on parent directories in R

我正试图在 R 中解决这个问题,但我会用任何编程语言来支持答案。

我有一个文件名矢量示例,例如所谓的 file_list

c("D:/example/sub1/session1/OD/CD/text.txt", "D:/example/sub2/session1/OD/CD/text.txt", 
"D:/example/sub3/session1/OD/CD/text.txt")

我想做的是移动和重命名文本文件,使其基于父目录的一部分,其中包含关于 subsession 的部分。所以第一个文件将被重命名 sub2_session1_text.txt 并与其他文本文件一起复制到一个名为 all_files

的新目录中

我正在努力解决如何重命名文件的一些细节问题。我正在尝试将 substrstr_locate_allpaste0 结合使用,以根据这些父目录复制和重命名文件。

定位向量file_list中每个元素的位置,构造substr的起始位置和结束位置

library(stringr)
ending<-str_locate_all(pattern="/OD",file_list)
starting <- str_locate_all(pattern="/sub", file_list)

然后我想以某种方式从这些列表中提取每个元素的那些模式的开始和结束位置,然后将其提供给 substr 以获取命名,然后依次使用 paste0 去创造 我想要的是

substr_naming_vector<-substr(file_list, start=starting[starting_position],stop=ending[starting_position])

但我不知道如何为列表编制索引,以便它知道如何为 starting_position 的每个元素正确编制索引。一旦我弄明白了,我会填写这样的内容

#paste the filenames into a vector that represents them being renamed in a new directory  
all_files <- paste0("D:/all_files/", substr_naming_vector)
#rename and copy the files 
file.copy(from = file_list, to = all_files)

这是一种方法。我假设你的文件总是被称为 text.txt.

library(stringr)

my_files <- c("D:/example/sub1/session1/OD/CD/text.txt",
              "D:/example/sub2/session1/OD/CD/text.txt", 
              "D:/example/sub3/session1/OD/CD/text.txt")

# get the sub information
subs <- str_extract(string = my_files,
                    pattern = "sub[0-9]")
# get the session information
sessions <- str_extract(string = my_files,
                        pattern = "session[0-9]")

# paste it all together
new_file_names <- paste("D:/all_files/", 
                        paste(subs, 
                              sessions, 
                              "text.txt",
                              sep = "_"),
                  sep = "")

file.copy(from = my_files, 
          to = new_file_names)

下面是一个使用正则表达式的例子,它变得更短了:

library(stringr)
library(magrittr)

all_dirs <-
  c("D:/example/sub1/session1/OD/CD/text.txt",
    "D:/example/sub2/session1/OD/CD/text.txt",
    "D:/example/sub3/session1/OD/CD/text.txt")

new_dirs <-
  all_dirs %>%
  # Match each group using regex
  str_match_all("D:/example/(.+)/(.+)/OD/CD/(.+)") %>%
  # Paste the matched groups into one path
  vapply(function(x) paste0(x[2:4], collapse = "_"), character(1)) %>%
  paste0("D:/all_files/", .)

# Copy them.
file.copy(all_dirs, new_dirs)