a script that looks and replaces a text in a .plist file in swift

You can use the FileManager and NSDictionary classes in Swift to read and modify a .plist file. Here's an example of how you can create a script that replaces a specific text in a .plist file:

main.swift
import Foundation

func replaceTextInPlistFile(filePath: String, searchText: String, replacementText: String) {
    // Check if the file exists
    guard FileManager.default.fileExists(atPath: filePath) else {
        print("File does not exist.")
        return
    }
    
    // Load the .plist file as a dictionary
    guard let plistDictionary = NSMutableDictionary(contentsOfFile: filePath) else {
        print("Failed to load .plist file.")
        return
    }
    
    // Iterate through each key-value pair in the plist dictionary
    for (key, value) in plistDictionary {
        if let stringValue = value as? String {
            if stringValue.contains(searchText) {
                // Replace the text
                plistDictionary[key] = stringValue.replacingOccurrences(of: searchText, with: replacementText)
            }
        }
    }
    
    // Save the modified dictionary back to the .plist file
    if plistDictionary.write(toFile: filePath, atomically: true) {
        print("Text replaced successfully.")
    } else {
        print("Failed to write .plist file.")
    }
}

// Usage example:
let filePath = "/path/to/your/plist/file.plist"
let searchText = "old text"
let replacementText = "new text"

replaceTextInPlistFile(filePath: filePath, searchText: searchText, replacementText: replacementText)
1332 chars
40 lines

Make sure to replace "/path/to/your/plist/file.plist" with the actual path to your .plist file, and provide the correct search and replacement texts.

Note: This script assumes that the .plist file contains a dictionary structure. If your .plist file has a different structure, you may need to modify the script accordingly.

related categories

gistlibby LogSnag