The Minimal Swift for Reading `stdin`

I needed to do some simple text file manipulation the other day and since it the command line was the obvious place for this, I started to use it as an excuse to learn bash, but then I quit that. I decided to fall back to Swift. I had to go back to a previous script I had written at one point that used Swift for stdin manipulation.

So, here in all its glory, is a very simple method for reading stdin into a single string.

#!/usr/bin/swift
import Foundation
var string = ""
while let thing = readLine(strippingNewline: false) {
    string  = thing
}

In order to run it without prior compilation:

xcrun swift readStdin.swift < textfile

To compile it, and then run the executable:

swiftc readStdin.swift -o readStdin
./readStdin < textfile

Advertisements