替代解决方案
之前的回答在R中提供了解决方案复制递归地从源到目标的文件夹。
根据你的问题,你需要移动文件夹并从根路径维护它们的相对子文件夹结构。
我知道这没什么大不了的,因为您可以简单地在文件夹上递归复制并删除原件,但是,一般来说,移动比复制快得多,这就是您所要求的,所以这就是我所拥有的。
我提出以下解决方案:
PowerShell 解决方案
最简单的解决方案是简单地运行:
# showing different ways of specifying paths
$fromDirs = @(
".older1"
"C:Path omyolder2"
"$env:USERPROFILEDocumentsTestDir"
)
$destDir = "$HOMEDesktop"
ForEach ($dir in $fromDirs) {
Move-Item -Path $dir -Destination $destDir -Force
}
另一个更复杂的 PowerShell 解决方案如下:
$fromDirs = @(
"C:Path omyolder1"
"C:Path omyolder2"
"C:Path omyolder3"
)
$toDir = "C:Path omydestination"
$fromDirs | ForEach-Object {
$fromDir = $_
$Files = Get-ChildItem -Path $fromDir -Recurse -File
$Files | ForEach-Object {
$File = $_
$RelativePath = $File.FullName.Replace($fromDir, '')
$Destination = Join-Path -Path $toDir -ChildPath $RelativePath
$DestinationDir = Split-Path -Path $Destination -Parent
if (-not (Test-Path -Path $DestinationDir)) {
New-Item -Path $DestinationDir -ItemType Directory -Force
}
Move-Item -Path $File.FullName -Destination $Destination -Force
}
}
这个更高级的解决方案处理移动递归路径时的相对论层次问题。
相对文件夹层次结构
为了保持相对的路径一致性(即移动文件夹和子文件夹时,您需要先创建相对路径结构,然后再移动/复制文件),需要比简单地运行 Move-Item -Path $fromDir -Destination $toDir -Force 更高级的解决方案,因为 Move-Item cmdlet 确实不支持递归(出于各种原因不应该)。
解决方案
在 R 中,我会使用 fs::dir_copy() 而不是 base R(我通常会避免这种做法),因为它在 Windows 中的文件系统管理实践以及它的 dir_copy() 函数在这种情况下比 base R file.copy() 更健壮。
require(fs)
fs::dir_copy(c("folder1", "folder2"), "DestinationFolder")
但要解决这个话题移动代替复制R 中最好的解决方案是使用基本 R 的 file.rename() 函数。
# this moves a directory from one location to another:
file.rename(folder_old_path, path_new)
对于具有子目录的多个目录:
to <- "todir"
froms <- c("dir1", "dir2")
tos <- paste0(to, "/", froms)
file.rename(froms, tos)
将导致“dir1”和“dir2”移动到“todir/dir1/" 和 "todir/dir2/”。
请注意,如果“todir”不存在,您需要先通过if (dir.exists(to)) { ... } 进行检查
复制与移动
就像在 UNIX 上一样,复制用于从一个地方复制到另一个地方,而移动用于移动文件或文件夹。移动不会有递归标志(即没有 -r 标志),因为它会自动将所有子文件夹和文件移动到指定目标的路径。但是,复制允许您指定递归选项以递归地复制目录。最后,要小心覆盖目标路径中预先存在的文件。
此外,如果您使用的是 Windows,则应使用正确的路径分隔符( 而不是 /;或者为了安全起见,只需使用双 \)。