将目录移动到包含空格的目录

时间:2017-08-13 11:49:58

标签: swift command-line

我正在使用脚本编写命令行脚本,我想将目录移动到另一个目录。我想将目录移动到的目录称为“模板文件”

我正试图以下列方式移动它

let templatePath = "\"~/Library/Developer/Xcode/Templates/File Templates/\""
let directoryName = "DTT\\ MVP"
do {
    try fileManager.moveItem(atPath: "\(currentPath)\(directoryName)", toPath: "\(templatePath)\(directoryName)")
} catch let error {
    print(error)
}

但它给了我以下错误

  

错误Domain = NSCocoaErrorDomain Code = 4“”DTT MVP“无法移动到   “文件模板”,因为前者不存在,或者   包含后者的文件夹不存在

有谁知道如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

有两个主要问题

  1. 您不得在Swift或Objective-C中转义路径。
  2. 波浪线不会自动扩展。
  3. 此外,强烈建议使用与URL相关的API,它提供方便(可靠)的方法来连接路径组件。

    假设currentURL是一个URL实例,我建议使用这种语法

    let fileManager = FileManager.default
    do {
        let libraryURL = try fileManager.url(for: .libraryDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
        let templateURL = libraryURL.appendingPathComponent("Developer/Xcode/Templates/File Templates")
        let directoryName = "DTT MVP"
        let source = currentURL.appendingPathComponent(directoryName)
        let destination = templateURL.appendingPathComponent(directoryName)
        try fileManager.moveItem(at: source, to: destination)
    }
    catch {
        print(error)
    }