Skip to content

Instantly share code, notes, and snippets.

@crisrojas
Created May 11, 2021 17:28
Show Gist options
  • Save crisrojas/6662f9fc78a99dc56c2c268a713a60ee to your computer and use it in GitHub Desktop.
Save crisrojas/6662f9fc78a99dc56c2c268a713a60ee to your computer and use it in GitHub Desktop.
Fixing Bear images when batch exporting (markdown)
import Foundation
func main() {
let fileManager = FileManager.default
let path = fileManager.currentDirectoryPath
let url = URL(string: "file://" + path)
guard let enumerator = fileManager.enumerator(atPath: path) else {
fatalError("Directory doesn't exist")
}
let pattern = "!\\[(.*?)\\]\\(.*?/(.*?)\\)"
while let file = enumerator.nextObject() as? String {
if file.hasSuffix(".md") {
let fileURL = url?.appendingPathComponent(file, isDirectory: false)
let filename = file.replacingOccurrences(of: ".md", with: "")
let assetFolder = filename
.replacingOccurrences(of: ", ", with: "%20")
.replacingOccurrences(of: " ", with: "%20")
do {
let contents = try String(contentsOfFile: file)
let regex = try NSRegularExpression(pattern: pattern, options: .caseInsensitive)
let range = NSRange(location: 0, length: contents.count)
let newContent = regex.stringByReplacingMatches(in: contents, options: [], range: range, withTemplate: "![](\(assetFolder)/$2)")
if let safeURL = fileURL {
try newContent.write(to: safeURL, atomically: true, encoding: String.Encoding.utf8)
}
} catch {
print ("writing file fail: \(error.localizedDescription)")
}
}
}
}
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment