一个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
相关推荐
杂雾无尘44 分钟前
掌握生死时速:苹果应用加急审核全攻略!
ios·swift·apple
晴风向上44 分钟前
mac mini m4安装node.js@16以下版本方法
macos·node.js
HarderCoder1 小时前
Swift 6.2 中的 `@concurrent`
ios·swift
JPCstorm2 小时前
Mac homebrew 安装教程
macos
FreeBuf_3 小时前
朝鲜APT组织使用Nim语言恶意软件对macOS发起隐秘Web3与加密货币攻击
macos·web3·策略模式
YungFan4 小时前
iOS26适配指南之通知
ios·swift
Digitally6 小时前
如何将信息从 iPhone 同步到Mac(完整步骤和示意图)
macos·ios·iphone
fengyun28916 小时前
Mac电脑 虚拟机 VMware Fusion13
macos·mac·虚拟机
前端张三6 小时前
mac 电脑安装Homebrew来安装npm与node成功后,安装nvm的流程
前端·macos·npm
大熊猫侯佩10 天前
消失的它:摆脱 SwiftUI 中“嵌入视图数量不能超过 10 个”限制的秘密
swiftui·swift·apple