Skip to content

Instantly share code, notes, and snippets.

@KoCMoHaBTa
Created May 4, 2016 12:26
Show Gist options
  • Save KoCMoHaBTa/6a066276d8273d15aa0b00ef6929dea8 to your computer and use it in GitHub Desktop.
Save KoCMoHaBTa/6a066276d8273d15aa0b00ef6929dea8 to your computer and use it in GitHub Desktop.
#!/usr/bin/swift
import Foundation
let Usage = "Usage: PrefixFiles.swift <directory> <prefix>"
extension String: ErrorType {}
extension NSURL {
var fileName: String? {
return self.URLByDeletingPathExtension?.lastPathComponent ?? self.lastPathComponent
}
func URLByRenamingFileName(name: String, ext: String? = nil) -> NSURL? {
let baseURL = self.URLByDeletingLastPathComponent
var result = baseURL?.URLByAppendingPathComponent(name)
if let ext = ext ?? self.pathExtension {
result = result?.URLByAppendingPathExtension(ext)
}
return result
}
}
do {
guard Process.arguments.count > 2 else {
throw Usage
}
let path = Process.arguments[1]
let dir = NSURL(fileURLWithPath: path)
let prefix = Process.arguments[2]
var files = try NSFileManager.defaultManager().contentsOfDirectoryAtURL(dir, includingPropertiesForKeys: nil, options: [.SkipsHiddenFiles, .SkipsPackageDescendants, .SkipsSubdirectoryDescendants])
try files.forEach({ (file) in
//prefix all files
let fileName = file.fileName!
let newName = prefix + fileName
let renamedFile = file.URLByRenamingFileName(newName)!
try NSFileManager.defaultManager().moveItemAtURL(file, toURL: renamedFile)
})
}
catch let e {
print(e)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment