一个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
相关推荐
皮卡车厘子1 天前
Mac 挂载目录
macos
良逍Ai出海1 天前
在 Windows & macOS 上安装 Claude Code,并使用第三方 Key 的完整教程
windows·macos
热爱生活的五柒1 天前
linux/mac/wsl如何使用claude code,并配置免费的硅基流动API?(官方的需要付费订阅)
linux·运维·macos
胖胖大王叫我来巡山1 天前
mac本地安装DataEase桌面版
macos
奋斗者1号1 天前
OpenClaw 部署方式对比:云端、WSL、Mac 本机、Ubuntu 虚拟机(2026年2月最新主流实践)
linux·ubuntu·macos
玉梅小洋1 天前
Android SDK 安装指南(MacOS 和 Windows)
android·windows·macos·sdk
2501_916007471 天前
没有 Mac 用户如何上架 App Store,IPA生成、证书与描述文件管理、跨平台上传
android·macos·ios·小程序·uni-app·iphone·webview
胖胖大王叫我来巡山1 天前
Mac通过源码安装部署SQLBOT
macos
June bug2 天前
【领域知识】广告全链路测试
macos·objective-c·cocoa
fendoudexiaoniao_ios2 天前
iOS 列表拖拽cell排序
ios·swift