I have a tab delimited text file called "data.txt" which looks like
data.txt
col2 col3 col4 col1
val1 val5 val9 val13
val2 val6 val10 val14
val3 val7 val11 val15
val4 val8 val12 val16
...
and I have an array col_order = [col1, col2, col3, col4]
The Objective is to rearrange the columns in "data.txt" according to the order in array "col_order" using a shell script.
Final Output
col1 col2 col3 col4
val13 val1 val5 val9
val14 val2 val6 val10
val15 val3 val7 val11
val16 val4 val8 val12
My Progress So Far
awk 'BEGIN{ORS=RS="\n"; S=OFS="\t"}{for (i=1; i<=NF; i++) {f[$i] = i}{ print $(f["col1"]),$(f["col2"]),$(f["col3"]),$(f["col4"])}}' data.txt> data_corrected.txt
The above statement works as expected, but the order is hard coded in the statement, Couldn't figure out how to take the order from array and pass it in the statement.
I'm open to any other approach as well.