Tom Wenseleers Tom Wenseleers - 1 year ago 107
R Question

R: efficiently delete all empty files in a directory

I am on the lookout for an efficient way to delete all empty files in a directory & subdirectories in R - what would be the best way forward? (I have directories with 100 000s of files, so it would have to be fast)

Answer Source
## Reproducible example, with two empty and one non-empty files
dir.create("A/B/C", recursive=TRUE)
dir.create("A/D", recursive=TRUE)
cat("", file="A/B/C/empty1.txt")
cat("", file="A/empty2.txt")
cat("111", file="A/D/notempty.txt")

## Get vector of all file names
ff <- dir("A", recursive=TRUE, full.names=TRUE)
## Extract vector of empty files' names
eff <- ff[[["size"]]==0]
## Remove empty files
unlink(eff, recursive=TRUE, force=FALSE)

## Check that it worked
dir("A", recursive=TRUE, full.names=TRUE)
# [1] "A/D/notempty.txt"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download