papelr
papelr

Reputation: 438

Remove white space from PDF names in a directory using R

I have a directory with some PDFs - and I need to get rid of white space in those titles. So, my first thought was to set the working directly to the appropriate place, and read in the directory:

blank <- list()
pdfs <- dir(pattern = "*.pdf")

And then loop through the PDFs:

for(i in 1:length(pdfs)) {
  gsub(" ", "-", pdfs)
}

But this doesn't get it done, and I have a feeling that I'm doing several things incorrectly:

  1. I'm not reading the directory correctly
  2. The for loop is not actually changing anything in the directory itself, but just in the list in R

I would appreciate the correct method! Thanks

Upvotes: 0

Views: 52

Answers (1)

Jozef
Jozef

Reputation: 2747

You could do something like:

# List all file paths ending in .pdf in mydir (not recursively)
fnames <- list.files(mydir, pattern = "\\.pdf$", full.names = TRUE)

# Create the new names replacing spaces to dashes in base names
newnames <- file.path(dirname(fnames), gsub(" ", "-", basename(fnames)))

# If happy with the newnames, rename
file.rename(fnames, newnames)

Upvotes: 1

Related Questions