Changing the order of columns in a CSV dataset

Post your working scripts, libraries and tools.
User avatar
flyingDman
Posts: 2817
Joined: 29 Sep 2013, 19:01

Changing the order of columns in a CSV dataset

30 Mar 2024, 17:26

I needed to change the order of columns in a CSV dataset and did not find a satisfactory solution here on the forum (please let me know if I overlooked something). To be clear: this does not sort the rows in CSV, it sorts the columns.
So if the columns are as follows 1,2,3,4,5,6 but I want 3,2,1,4,5,6 the following script will do that.
Two lines need some additional commentary.
Line 11: if you want to move col3 in 1st position use ordr := [3]. By doing that col2 moves to 3rd position. So if you want to move that column back to the 2nd position, you'll use ordr := [3,3]. Other columns will be unaffected. The resulting order will be 3,2,1,4,5,6. Using ordr := [] does not change the order of columns. If the desired order 6,5,4,3,2,1 use ordr := [6,6,6,6,6] (note: moving 5 columns will automatically determine the rank of the last column).
Line 29. What you remove there (y) is inserted here (x).
In the spoiler is a similar script for showing the data in a Listview.
I have used it on a CSV with 100,000 rows. Impact on speed seems to be minimal.

Code: Select all

#Requires AutoHotkey v2.0

str := "
(
col1,col2,col3,col4,col5,col6
a,b,c,d,e,"f,g"
aa,bb,cc,dd,ee,ff
aaa,bbb,ccc,ddd,eee,fff
)"

ordr := [3,3]												; new order of columns; ordr := [] leaves order unchanged
for x,y in strsplit(trim(str,"`r`n"),"`n","`r")				; parses the str by row
	rw := csvprs(y,ordr), nstr .= join(rw) "`n"				; parses + reorders elements in each row + joins them
msgbox nstr

join(arr,del:=",")
	{
	for x,y in arr	
		lst .= (x>1?del:"") (z := instr(y,",")?'"':"") y z 	; reestablishes the "" around cells that include a comma
	return lst
	}

CSVprs(item,ordr)											; parse and sort function 
	{
	row := []
	loop Parse item, "CSV"
		row.push(A_loopfield)	
	for x,y in ordr
		row.insertat(x,row.removeat(y))						; swaps order of columns
	return row                                              ; an array is returned
	}
Spoiler
Last edited by flyingDman on 01 Apr 2024, 12:31, edited 1 time in total.
14.3 & 1.3.7

Return to “Scripts and Functions (v2)”

Who is online

Users browsing this forum: No registered users and 47 guests