ebb
ebb

Reputation: 274

R rename files keeping part of original name

I'm trying to rename all files in a folder (about 7,000 files) files with just a portion of their original name.

The initial fip code is a 4 or 5 digit code that identifies counties, and is different for every file in the folder. The rest of the name in the original files is the state_county_lat_lon of every file.

For example:

Original name:

"5081_Illinois_Jefferson_-88.9255_38.3024_-88.75_38.25.wth"
"7083_Illinois_Jersey_-90.3424_39.0953_-90.25_39.25.wth"
"11085_Illinois_Jo_Daviess_-90.196_42.3686_-90.25_42.25.wth"
"13087_Illinois_Johnson_-88.8788_37.4559_-88.75_37.25.wth"
"17089_Illinois_Kane_-88.4342_41.9418_-88.25_41.75.wth"

And I need it to rename with just the initial code (fips):

"5081.wth"
"7083.wth"
"11085.wth"
"13087.wth"
"17089.wth"

I've tried by using the list.files and file.rename functions, but I do not know how to identify the code name out of he full name. Some kind of a "wildcard" could work, but don't know how to apply those properly because they all have the same pattern but differ in content.

This is what I've tried this far:

setwd("C:/Users/xxx")
Files <- list.files(path = "C:/Users/xxx", pattern = "fips_*.wth" all.files = TRUE)
newName <- paste("fips",".wth", sep = "")

for (x in length(Files)) {
  file.rename(nFiles,newName)}

I've also tried with the "sub" function as follows:

setwd("C:/Users/xxxx")
Files <- list.files(path = "C:/Users/xxxx", all.files = TRUE)
for (x in length(Files)) {
  sub("_*", ".wth", Files)}

but get Error in as.character(x) : cannot coerce type 'closure' to vector of type 'character'

OR

setwd("C:/Users/xxxx")
Files <- list.files(path = "C:/Users/xxxx", all.files = TRUE)
for (x in length(Files)) {
  sub("^(\\d+)_.*", "\\1.wth", file)}

Which runs without errors but does nothing to the names in the file.

I could use any help. Thanks

Upvotes: 0

Views: 2344

Answers (1)

cuttlefish44
cuttlefish44

Reputation: 6796

Here is my example.

Preparation for data to use;

dir.create("test_dir")

data_sets <- c("5081_Illinois_Jefferson_-88.9255_38.3024_-88.75_38.25.wth",
  "7083_Illinois_Jersey_-90.3424_39.0953_-90.25_39.25.wth",
  "11085_Illinois_Jo_Daviess_-90.196_42.3686_-90.25_42.25.wth",
  "13087_Illinois_Johnson_-88.8788_37.4559_-88.75_37.25.wth",
  "17089_Illinois_Kane_-88.4342_41.9418_-88.25_41.75.wth")

setwd("test_dir")
file.create(data_sets)

Rename the files;

Files <- list.files(all.files = TRUE, pattern = ".wth")
newName <- sub("^(\\d+)_.*", "\\1.wth", Files)

file.rename(Files, newName)

Upvotes: 1

Related Questions