Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@douglashill
Created February 11, 2020 16:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save douglashill/3e4323bcff98e41ac04023cf78fcb8b7 to your computer and use it in GitHub Desktop.
Save douglashill/3e4323bcff98e41ac04023cf78fcb8b7 to your computer and use it in GitHub Desktop.
Swift script helper to find and replace an array of substitutions.
/// Performs a textual find and replace with the specified substitutions on all files in directory (recursive) that have the specified filename extensions.
func find(_ substitutions: [(find: String, replace: String)], allowedExtensions: Set<String>, directory rootURL: URL) {
let fileURLs = FileManager.default.enumerator(at: rootURL, includingPropertiesForKeys: nil)!.map {
$0 as! URL
}
.filter {
$0.hasDirectoryPath == false
}
.filter {
allowedExtensions.contains($0.pathExtension)
}
for url in fileURLs {
var encoding = String.Encoding.japaneseEUC
let contents = try! String(contentsOf: url, usedEncoding: &encoding)
let modifiedContents = substitutions.reduce(contents) { contents, substitution -> String in
contents.replacingOccurrences(of: substitution.find, with: substitution.replace)
}
if modifiedContents != contents {
try! modifiedContents.write(to: url, atomically: false, encoding: encoding)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment