简体   繁体   中英

How to replace backslash to forward slash for entire CSV file in R?

I have a simple R script:

file1 <- read.csv2("D:/Home/file1.csv", strip.white = TRUE, header = FALSE)
file2 <- read.csv2("D:/Home/file2.csv", strip.white = TRUE, header = FALSE)

df <- merge(file1, file2, by.x = c(2), by.y = c(1)) 

df2 <- data.frame(new_col = paste('"', df$V2, '#', df$V1, '#', df$V2.y, '",', sep = ""))

write.table(df2, append = FALSE, file = outFile, sep = "#", quote = FALSE, row.names = FALSE, col.names = FALSE)

File 1 is like this:

100;folder/path/myfile.mp3
101;folder/path/anotherfile.mp3
102;folder/path/finalfile.mp3

File 2 is like this:

folder\path\myfile;64
folder\path\anotherfile;58
folder\path\finalfile;34

So my script merges file 1 with file 2 based on the path column (second column in file 1 and 1st column in file 2). It does this fine if both files have forward slashes for each row.

The problem is that file 1 has forward slashes and file 2 has backslashes so the merge isn't working.

How do I make it so that the merge will work given that they both use different slashes? In other words, how can I convert all of file2 to use forward slashes prior to the merge? I need the final result to use forward slashes, not backslashes.

I have looked through lots of other questions and answers and replacing backslashes to forward slashes has been asked before but only on strings. I can't find a question asking how to replace every slash in the whole source CSV file. So I don't believe this is a duplicate.

Many thanks.

This should work:

file2$column = gsub(pattern = "\\\\", replacement = "/", x = file2$column)

Replace column in my code with whatever the column name is.

Another regex could be the following.

x <- 'a\\b\\c'
gsub('[\\]', '/', x)
#[1] "a/b/c"

Or, using argument fixed = TRUE ,

gsub('\\', '/', x, fixed = TRUE)
#[1] "a/b/c"

Now it's a matter of applying the above to the column(s) of the dataframe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM