Created
May 11, 2021 17:28
-
-
Save crisrojas/6662f9fc78a99dc56c2c268a713a60ee to your computer and use it in GitHub Desktop.
Fixing Bear images when batch exporting (markdown)
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
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