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].
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.
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].
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:
#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]; create new order of columns; ;ordr := [] would leave the order unchanged
for x,y in strsplit(trim(str,"`r`n"),"`n","`r"); populates the LV
rw := csvprs(y,ordr), nstr .= join(rw) "`n"; parses and reorders the elements of each row
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
Statistics: Posted by flyingDman — Today, 17:26