Commit 84625e20 authored by Andrey Vetlugin's avatar Andrey Vetlugin

Initial commit

parents
"name","email","company"
"Andrey","andrey@cc.de",""
"Sems","sems@cc.de","cc"
#!/usr/bin/env groovy
String unescape(String escaped) {
return escaped
}
// TODO implement this
//assert 'asdf' == unescape('"asdf"')
//assert 'as"df' == unescape('"as""df"')
//assert "" == '""'
assert unescape('asdf') == 'asdf'
List<String> splitLine(String line) {
return line.split(/,/)
}
assert splitLine('a,b,c') == ['a', 'b', 'c']
List<String> lines = new File('data.csv').readLines()
Set<String> headers = []
// get headers
splitLine(lines.remove(0)).each {
headers.add(it)
}
println headers
// TODO get lines
// TODO split lines into values
List<Map<String, String>> parsedLines = []
lines.each { line ->
Map<String, String> lineMap = [:]
def values = splitLine(line)
headers.eachWithIndex { header, index ->
lineMap[header] = values[index]
}
parsedLines << lineMap
}
println parsedLines.dump()
println parsedLines
#!/usr/bin/env groovy
String escape(String unescaped) {
if (!unescaped) {
return '""'
}
return '"' + unescaped.replaceAll(~/"/, '""') + '"'
}
assert escape('asdf') == '"asdf"'
assert escape('as"df') == '"as""df"'
assert escape(null) == '""'
def writeToCsv(List<Map<String, String>> inputMap) {
// print headers
Set<String> headers = []
inputMap.each {
it.each { k, v ->
headers.add(k)
}
}
println headers.collect {
escape(it)
}.join(",")
// print values as CSV
inputMap.each { Map<String, String> lineMap ->
println headers.collect { String key ->
escape(lineMap[key])
}.join(',')
}
}
List<Map<String, String>> inputMap = [
[name: 'Andrey', email: 'andrey@cc.de'],
[name: 'Sems', email: 'sems@cc.de', company: 'cc']
]
writeToCsv(inputMap)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment