一个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
相关推荐
未来侦察班9 小时前
一晃13年过去了,苹果的Airdrop依然很坚挺。
macos·ios·苹果vision pro
普通网友13 小时前
苹果笔记本(Mac)连接手机完全指南
macos·智能手机
锐意无限14 小时前
Swift 扩展归纳--- UIView
开发语言·ios·swift
Aftery的博客15 小时前
Xcode运行报错:SDK does not contain ‘libarclite‘ at the path
macos·cocoa·xcode
文件夹__iOS19 小时前
AsyncStream 进阶实战:SwiftUI 全局消息流极简实现
ios·swiftui·swift
楚轩努力变强1 天前
iOS 自动化环境配置指南 (Appium + WebDriverAgent)
javascript·学习·macos·ios·appium·自动化
猫头虎2 天前
如何解决 OpenClaw “Pairing required” 报错:两种官方解决方案详解
网络·windows·网络协议·macos·智能路由器·pip·scipy
皮卡车厘子3 天前
Mac 挂载目录
macos
良逍Ai出海3 天前
在 Windows & macOS 上安装 Claude Code,并使用第三方 Key 的完整教程
windows·macos
热爱生活的五柒3 天前
linux/mac/wsl如何使用claude code,并配置免费的硅基流动API?(官方的需要付费订阅)
linux·运维·macos