Skip to content

Instantly share code, notes, and snippets.

@pud
Last active January 12, 2019 16:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pud/84f660b321a350024466 to your computer and use it in GitHub Desktop.
Save pud/84f660b321a350024466 to your computer and use it in GitHub Desktop.
<!---
convert comma separated values (CSV) to tab-separated values (TSV)
while preserving commas in qualified strings
--->
<cffunction name="CSVtoTSV" output="no">
<cfargument name="csv" required="yes" type="string">
<cfset csv = replace(csv, ',', ', ', 'all')> <!--- make sure to trim() values when you use them later --->
<!--- find qualified strings --->
<cfset qualified = reMatch('[\b ,](".*?")',csv)>
<!--- /find qualified strings --->
<cfdump var="#csv#">
<cfloop array="#qualified#" index="x">
<hr>
<cfset originalPhrase = x>
<cfset phrase = x>
<cfif mid(phrase,1,1) eq ','>
<cfset phrase = right(phrase,len(phrase)-1)>
</cfif>
<!--- replace the commas in qualified values with chr(30) --->
<cfset phrase = replaceNoCase(phrase,',',chr(30),'all')>
<!--- /replace the commas in qualified values with chr(30) --->
<cfset phrase = replaceNoCase(phrase,'"','','all')>
Original: #originalPhrase#<br>
Phrase: #phrase#<br>
<cfif mid(originalPhrase,1,1) eq ','>
<cfset phrase = ",#phrase#">
</cfif>
<cfset csv = replace(csv,originalPhrase,phrase,'all')>
</cfloop>
<hr>
<!--- convert all the commas to tabs --->
<cfset csv = replace(csv,',',chr(9),'all')>
<!--- /convert all the commas to tabs --->
<!--- convert the chr(30)'s back into commas --->
<cfset csv = replace(csv,chr(30),',','all')>
<!--- /convert the chr(30)'s back into commas --->
<cfdump var="#csv#" label="new">
<cfreturn csv>
</cffunction>
@lesirvin
Copy link

Thanks for this. Does this preserve a number of empty fields in a row? Ex... if I have:
blah,blah,,,,,,,,,,,,,,,blah
will the empty fields convert to the similar number of tabs?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment