👓

【swift】processでgrepとnkfをpipeする

2021/07/28に公開

概要

processを利用して
grepコマンドを発行 & grepの標準出力結果をnkfでUTF8に変換して標準出力表示してみます。

前提

nkfコマンドはインストール済みであること。
入ってない場合はbrewとかでインストールします。

brew install nkf

コード

func grep_nkf(searchStr: String, searchPath: String) {
        let pipe = Pipe()
        let pipe2 = Pipe()
        
        // grepの設定
        let grep = Process()
            grep.launchPath = "/usr/bin/grep"
            grep.arguments = ["-r",\(searchStr), \(searchPath)]
	    // grepコマンドの結果をpipeでストリーム保持
            grep.standardOutput = pipe
        // nkf(文字コード変換)の設定
        // grep の後ろにpipeで接続する発行イメージ<grep -r searchStr searchPath | nkf -w>
        let nkf = Process()
            nkf.launchPath = "/usr/local/bin/nkf"
            nkf.arguments = ["-w"]
	    // pipeで保持しているgrepの結果を標準入力として渡す
            nkf.standardInput = pipe
	    // nkfコマンドの結果をpipe2でストリーム保持
            nkf.standardOutput = pipe2

        // grepの終了ハンドラ。grepが終わったらnkfを発行する。
        grep.terminationHandler = { (_) in
            nkf.launch()
        }
        // grep実行
        grep.launch()
        // コマンド結果が入っている標準出力ストリームを変数で受け取る
        let data = pipe2.fileHandleForReading.readDataToEndOfFile()
	// ストリームデータを文字列に変換する。一応エンコードでUTF8も指定。
        guard let output = String(data: data, encoding: .utf8) else {return}
	// 標準出力
        Swift.print(output)
}

grep_nkf("検索文言", "検索パス") // 関数の呼び出し

Discussion