Created
February 11, 2020 16:13
-
-
Save douglashill/3e4323bcff98e41ac04023cf78fcb8b7 to your computer and use it in GitHub Desktop.
Swift script helper to find and replace an array of substitutions.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// 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