假设我有一个文本文件text.txt
,其中包含使用单个空格(而非制表符)缩进的多行文本,如:
My folder1/
My folder2/
My folder3/
file1.md
My folder4/
例如,实际目录模板可能如下所示:
Proposal/
rules/
proposal/
document.tex
figs/
tabs/
ref/
log/
src/
master.r
crdat/
andat/
temp/
data/
raw/
clean/
Admin/
budget/
contract/
invoices/
receipts/
team/
hiring/
vitae/
gantt/
forms/
misc/
Study/
document.tex
figs/
tabs/
ref/
log/
src/
master.r
crdat/
andat/
temp/
data/
raw/
clean/
Dissemination/
presentations/
conference1/
submission.md
slides.tex
notes.md
admin/
registration/
travel/
receipts/
program/
forms/
conference2/
manuscripts/
journal1/
submission/
letter_v1.tex
manuscript_v1.pdf
replication_v1.zip
comments/
reviewer1.txt
R&R/
letter_v2.tex
manuscript_v2.tex
diff.tex
replication_v2.zip
journal2/
master_notes.md
TODOs.md
README.md
本质上,该文件是目录结构的模板。该模板可由用户设置。她可以为不同的项目使用不同的模板,并且名称是通用的。唯一的限制是使用空格建立层次结构,文件夹以正斜杠结束。
我想编写一个函数,它将任何这样的目录模板作为输入,并在当前工作目录中创建一个目录结构。伪代码如下:
lines <- readLines(text.txt)
last.indent <- 0
for (i in lines) {
Create directory structure by looking at leading character and last characters (folders end in /)
using dir.create(i) or file.create(i)
}
答案 0 :(得分:0)
我怀疑你实际上正在做一些更复杂的事情。在这种情况下,这可能不起作用:
library(qdap); library(reports)
x <- readLines(n=13) ## you'd read this in from a file I assume
My folder1/
My folder2/
My folder3/
file1.md
My folder4/
My folder1b/
My folder2/
My folder3/
file1.zip
My folder1c/
My folder2/
My folder3/
file1.pdf
## You didn't ask for this but this keeps the direcories contained
new <- folder(new)
setwd(new)
dirs <- which(substring(x, 1, 1) != " ")
lens <- lapply(seq_along(dirs), function(i) {
dirs[i]:c(tail(dirs - 1, -1), length(x))[i]
})
paths <- split(x, rep(1:length(dirs), sapply(lens, length)))
path <- sapply(paths, function(x) paste(Trim(x), collapse=""))
is.dir <- sapply(path, function(x) substring(x, nchar(x))) == "/"
lapply(seq_along(is.dir), function(i){
out <- folder(folder.name =ifelse(is.dir[i],
path[i], dirname(path[i])))
if(!is.dir[i]) {
cat("", file = paste0(path[i], "_hold_.txt"))
}
})