Skip to content

Instantly share code, notes, and snippets.

@guidomb
Last active October 25, 2017 19:10
Show Gist options
  • Save guidomb/9c3ac4cb21f21f56480c9c273bfed63b to your computer and use it in GitHub Desktop.
Save guidomb/9c3ac4cb21f21f56480c9c273bfed63b to your computer and use it in GitHub Desktop.
import Foundation
import Darwin
if CommandLine.argc < 2 {
print("input file missing")
exit(1)
}
if CommandLine.argc < 3 {
print("column name missing")
exit(1)
}
if CommandLine.argc < 4 {
print("replacement value missing")
exit(1)
}
if CommandLine.argc < 5 {
print("output file missing")
exit(1)
}
let inputFileName = CommandLine.arguments[1]
let columnName = CommandLine.arguments[2]
let replacementValue = CommandLine.arguments[3]
let outputFileName = CommandLine.arguments[4]
let inputFileContent = try! String(contentsOfFile: inputFileName, encoding: .utf8)
.split(separator: "\r\n")
let columnNames = inputFileContent[0].split(separator: ",").map { String($0) }
guard let columnNameIndex = columnNames.index(of: columnName) else {
print("column name doesn’t exists in the input file")
exit(1)
}
func replaceValues(in rows: ArraySlice<Substring>, with replacement: String, forColumnAt columnIndex: Int) -> [String] {
return rows.map { replaceValue(in: String($0), with: replacement, forColumnAt: columnIndex) }
}
func replaceValue(in row: String, with replacement: String, forColumnAt columnIndex: Int) -> String {
var values = row.split(separator: ",").map { String($0) }
values[columnIndex] = replacementValue
return values.joined(separator: ",")
}
let header = String(inputFileContent[0]) + "\r\n"
let body = replaceValues(
in: inputFileContent[1...],
with: replacementValue,
forColumnAt: columnNameIndex
).joined(separator: "\r\n")
try! (header + body).write(toFile: outputFileName, atomically: true, encoding: .utf8)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment