DaphFab
DaphFab

Reputation: 73

compare filenames in 2 folders and move the unmatched files to a separate folder in

I have 2 folders A and B with 5000 and 6000 files respectively. Folder B is a subset of the folder A. I need to compare these two folders and moves the unmatched files to a separate folder C. How could this be done in R by just comparing the filenames and moving them

Upvotes: 2

Views: 1337

Answers (1)

Val
Val

Reputation: 7023

First you'll need to list the files in their respective directory (here with the directory for A as example:

flsA <- list.files(dirA,patt,full.names=TRUE, recursive=FALSE) 

With patt you can specify a pattern string, like a file extension, e.g. ".txt$" (note the $ at the end telling R it's the end of the filename).

If there are sub-directories you want to include, you can set recursive to TRUE.

The full.names option gives the full paths and is necessary for moving files later.

When you have both directories listed, you can compare the contained files with the functions basename and %in%:

ix <- basename(flsA) %in% basename(flsB)

This will give you a logical vector (TRUE for files in both A and B) which you can then use for indexing the files you want:

to_move <- flsA[!ix]

I'm using the ! operator to reverse the logical vector as I want the files which are not in both directories.

Finally you can lapply the function you want to your files, e.g.:

lapply(to_move, function(x) file.copy(x,new.dir_C)

Once they are copied correctly, you could use file.remove to get rid of the originals:

lapply (to_move,file.remove)

Upvotes: 2

Related Questions