title: Copy and rename Specific Files based on parent directories in R
body: <p>I am attempting to solve this issue in R, but I'll upvote answers in any programming language. </p>
  
  <p>I have an example vector of filenames like so called <code>file_list</code></p>
  
  <pre><code>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")
  </code></pre>
  
  <p>What I'm trying to do is move and rename the text files to be based on the part of the parent directory that contains the part about <code>sub</code> and <code>session</code>. So the first file would be renamed <code>sub2_session1_text.txt</code>and be copied along with the other text files to just 1 new directory called <code>all_files</code></p>
  
  <p>I'm struggling with some of the specifics of how to rename the file. I'm trying to use <code>substr</code> combined with <code>str_locate_all</code> and <code>paste0</code> to copy and rename the files based on these parent directories.  </p>
  
  <p>Locate the position in each element of the vector <code>file_list</code> to construct starting and ending position for <code>substr</code> </p>
  
  <pre><code>library(stringr)
  ending&lt;-str_locate_all(pattern="/OD",file_list)
  starting &lt;- str_locate_all(pattern="/sub", file_list)
  </code></pre>
  
  <p>I then want to somehow pull out of those lists the starting and ending position of those patterns for each element and then feed it to <code>substr</code> to get the naming down and then in turn use <code>paste0</code> to create 
  What I'd like is something like </p>
  
  <pre><code>substr_naming_vector&lt;-substr(file_list, start=starting[starting_position],stop=ending[starting_position])
  </code></pre>
  
  <p>but I don't know how to index the list such that it can know how to correctly index for each element the <code>starting_position</code>. Once I figure that out I'd fill in something like this </p>
  
  <pre><code>#paste the filenames into a vector that represents them being renamed in a new directory  
  all_files &lt;- paste0("D:/all_files/", substr_naming_vector)
  #rename and copy the files 
  file.copy(from = file_list, to = all_files)
  </code></pre>