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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s