Skip to content

Instantly share code, notes, and snippets.

@orestis
Last active November 26, 2018 16:01
Show Gist options
  • Save orestis/f5ed37783a7a3e0c6b6e51aa9b30c44e to your computer and use it in GitHub Desktop.
Save orestis/f5ed37783a7a3e0c6b6e51aa9b30c44e to your computer and use it in GitHub Desktop.
(ns scratch
(:require [clojure.string :as str]))
(defn csv-split [line]
(str/split line #","))
(defn replace-col [cols idx s]
(map-indexed (fn [i x] (if (= i idx) s x)) cols))
(defn index-of [coll value]
(first (keep-indexed #(when (= %2 value) %1) coll)))
(defn run [input-str col replacement]
(let [[header & rows] (str/split-lines input-str)
col-idx (index-of (csv-split header) col)
output-seq (->> rows
(map #(replace-col (csv-split %) col-idx replacement))
(cons [header]))]
(->> output-seq
(map #(str/join "," %))
(str/join "\n"))))
(def input
"name,surname,city,country
Adam,Jones,Manchester,UK
Joe,Doe,Cracow,Poland
Michael,Smith,Paris,France
Alex,McNeil,Gdynia,Poland")
(def output
"name,surname,city,country
Adam,Jones,London,UK
Joe,Doe,London,Poland
Michael,Smith,London,France
Alex,McNeil,London,Poland")
(= output (run input "city" "London"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment