Ali Anis
Ali Anis

Reputation: 63

Rename list of files with his last characters

I want to rename my data frame with the last characters of his actual name. How can i do this please ?

#Importing file 
temp = list.files(pattern="*.csv")
for (i in 1:length(temp)) assign(temp[i], read.csv2(temp[i]))

an exemple of file imported is:

XXX__Xxxx_Xxxxx__XXX-X.csv

i want to change it to:

XXX-X.csv

How can i make loop to read a specific XXX-X.csv please?

Upvotes: 3

Views: 68

Answers (2)

TarJae
TarJae

Reputation: 79164

Maybe we could use str_sub from stringr package:

library(stringr)
str_sub(str1,-9,-1)

Output:

[1] "XXX-X.csv"

Upvotes: 2

akrun
akrun

Reputation: 887511

We could use trimws and specify the whitespace to match characters (.*) till the one or more underscore (_+) to remove those

trimws(str1, whitespace = ".*_+")
[1] "XXX-X.csv"

There is no need for a loop as these are vectorized functions

trimws(temp, whitespace = ".*_+")

Upvotes: 2

Related Questions