Changing file names

Suppose I have many PDF files in ./reports, where all the file names start with my-report then date. For example, my-report-20200901.pdf.

  1. How do I replace my-report with doc e.g. my-report-20200901.pdf will become doc-20200901.pdf?
  2. How do I keep dates only i.e. file name would be 20200901.pdf

You could be interested in fs :package: for file manipulation.

There should be a renaming function.

You can use regex with grep or gsub, or stringr :package: to do the file replacement; stringr::str_replace or stringr::str_remove for example

This should be what is needed for this kind of task.

1 Like

Here is a solution which should work cross-platform.

old <- dir("./reports",
           full.names = TRUE,
  = TRUE)
file.rename(old, gsub("my-report", "doc", old))
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.