Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

swap columns and it's column values

Status
Not open for further replies.

pigna

Programmer
Nov 9, 2006
10
NL
A certain progam provides a column based output but column order is different for systems/versions.
Simplefied something like this:

System A:

ColB ColA ColC ColD
1 4 1 1
2 2 5 4
1 3 0 1

System B:

ColD ColB ColA ColC
1 2 0 4
1 7 5 1
1 2 0 1


To process these files I need to swap columns and its values. Preferred way is to swap columns and set them in alphabetically order so they can be processed together in an external program:

So output file for System A would become

ColA ColB ColC ColD
4 1 1 1
2 2 5 4
3 1 0 1

Output file System B:

ColA ColB ColC ColD
0 2 4 1
5 7 1 1
0 2 1 1


Any help is much appreciated!
 
I'm sure there is a more elegant solution than this, but see how it goes:

Code:
awk '
NR==1 {
        for (i=1;i<=NF;i++) { col[$i]=i ; colsorted[i]=$i }
        ncols=asort(colsorted)
}
{
        for (i=1; i<=ncols; i++) { printf($col[colsorted[i]] OFS); }
        print ""
}
'

Annihilannic.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top