Convert CSV records to TSV: Difference between revisions

julia example
(→‎jq: typo)
(julia example)
Line 240:
* Backquotes are uniformly duplicated.
* Until recently gojq did not handle NUL (#x0) properly.
 
=={{header|Julia}}==
{{trans|Phix}}
<syntaxhighlight lang="julia">function csv_tsv(str)
p = split(str, ",")
for (i, f) in enumerate(p)
if count(==('"'), f) > 1
p[i] = replace(strip(f, [' ', '"']), "\"\"" => "\"")
elseif f == "\""
p[i] = ""
end
end
t = join(p,"<TAB>")
s = replace(str, "\\" => "\\\\", "\t" => "\\t", "\0" => "\\0", "\n" => "\\n")
t = replace(t, "\\" => "\\\\", "\t" => "\\t", "\0" => "\\0", "\n" => "\\n")
return s, t
end
 
for test_string in [
"""a,"b\"""",
"""\"a","b""c\"""",
"",
",a",
"a,\"",
" a , \"b\"",
"""\"12",34""",
"a\tb,", # That is a TAB character
raw"a\tb", # That is not
raw"a\n\rb",
"a\0b", # That is a NUL character
"a\nb", # That is a LF (linefeed) character
raw"a\b"]
csv, tsv = csv_tsv(test_string)
println(lpad(csv, 12), " => ", tsv)
end
</syntaxhighlight>{{out}}
<pre>
a,"b" => a<TAB>b
"a","b""c" => a<TAB>b"c
=>
,a => <TAB>a
a," => a<TAB>
a , "b" => a <TAB>b
"12",34 => 12<TAB>34
a\tb, => a\tb<TAB>
a\\tb => a\\tb
a\\n\\rb => a\\n\\rb
a\0b => a\0b
a\nb => a\nb
a\\b => a\\b
</pre>
 
=={{header|Phix}}==
4,108

edits