一个macOS上用的swift文件脚本的模版:输入文件文本转换后输出到文件

本文介绍一种简单的swift脚本实现方案和执行方法。脚本可以读取文件内容,需要读者自行实现内容转换,然后脚本将结果输出到指定输出文件。

脚本模版

其中getResult函数需要读者按照自己需要实现。

swift 复制代码
import Foundation

final class TestOnlySwift {

    //入参为输入文案,返回为输出文案,改这个函数实现就行了
    func getResult(str:String)->String {
        return str + "1"
    }
    
    //下面的可以不改
    
    func run(jsonFile: String, outputFile: String) {
        let pwd = shell("pwd")
        print("Working in \(pwd)")

        do {
            let jsonUrl = URL(fileURLWithPath: pwd).appendingPathComponent(jsonFile)
            
            guard FileManager.default.fileExists(atPath: jsonUrl.path) else {
                print("JSON file \(jsonUrl.path) does not exists!")
                exit(0)
            }
            
            let inputStr = try String(contentsOfFile: jsonUrl.path)
            let outputStr = getResult(str: inputStr)
            try outputStr.write(to: URL(fileURLWithPath: pwd).appendingPathComponent(outputFile), atomically: true, encoding: .utf8)
            print("Success")
        } catch {
            print("\(error)")
        }
    }

    @discardableResult
    func shell(_ command: String) -> String {
        let task = Process()
        let pipe = Pipe()
        
        task.standardOutput = pipe
        task.standardError = pipe
        task.arguments = ["-c", command]
        task.launchPath = "/bin/zsh"
        task.launch()
        
        let data = pipe.fileHandleForReading.readDataToEndOfFile()
        let output = String(data: data, encoding: .utf8)!
        
        return output.trimmingCharacters(in: .newlines)
    }

}

let namedArguments = UserDefaults.standard
guard let jsonFile = namedArguments.string(forKey: "i") else {
    print("Provide json crash file name with -i flag")
    exit(0)
}
guard let outputFile = namedArguments.string(forKey: "o") else {
    print("Provide output file name with -o flag")
    exit(0)
}
TestOnlySwift().run(jsonFile: jsonFile, outputFile: outputFile)

使用方式

把上面代码写到TestOnlySwift.swift文件中,跟输入文件放(inputFile)到一个目录,在终端如下执行命令,结果会放在outputFile。

复制代码
swift TestOnlySwift.swift -i inputFile -o outputFile
相关推荐
Cosmoshhhyyy5 小时前
mac环境下安装git并配置密钥等
git·macos
Swift社区6 小时前
Swift 实战:实现一个简化版的 Twitter(LeetCode 355)
leetcode·swift·twitter
HarderCoder7 小时前
当Swift Codable遇到缺失字段:优雅解决数据解码难题
swift
肥肥呀呀呀11 小时前
mac 安卓模拟器 blueStacks
macos
csdn_aspnet11 小时前
如何在 MacOS 上安装 SQL Server
macos·sqlserver
YungFan1 天前
iOS26适配指南之UIButton
ios·swift
共享家95272 天前
linux-数据链路层
linux·网络·macos
CZIDC2 天前
MacOS字体看起来比在 Windows 上更好?
macos
Cosmoshhhyyy2 天前
linux远程部署dify和mac本地部署dify
linux·运维·macos
行星0082 天前
mac 通过homebrew 安装和使用nvm
macos·npm·node.js