How to exchange two columns in a table?

Tim Chase blinux.list at thechases.com
Sun Jan 7 13:51:26 UTC 2007


> Thank you! It's just a tab-delimited text file.


Ah, okay.  There are a couple different ways to do it:

1) with sed:

sed 's/^\([^\t]*\t[^\t]*\t\)\([^\t]*\t\)\([^\t]*\t\)\(.*\)/\1\3\2\4/'

That's a bit ugly, but fairly easy to modify.  There are four 
things wrapped in "\(...\)".  The first pair contains a 
"[^\t]*\t" for each field to be skipped before the column of 
interest.  The second and third pairs simply snag the contents of 
the column you want.  The fourth pair snags the remainder of the 
line.  It then does a substitution, stitching those parts back 
together, swapping the 2nd and 3rd grouping (the columns of 
interest).

2) with awk:
awk '{
	output = "";
	split($0, a);
	temp=a[3]; a[3]=a[4]; a[4]=temp;
	for (i=1; i <= length(a); i++){
		if (i-1) output = output "\t";
		output = output i a[i]};
		print output
	}'

The advantage to the awk version is that it is easier to read 
(it's much easier to tell that this is swapping columns 3 and 4 
compared to the sed version), and easier to modify.  You can even 
put that statement (the contents of the quote) in a file such as 
"swapcols.awk" and call it with

	awk -f swapcols.awk in.txt > out.txt

Or even prefix the file with a shebang line, something like

	#!/usr/bin/awk -f

and make the file executable if you plan to swap the same two 
columns more than once.

3) with Python

 >>> outfile = file("out.txt", "w")
 >>> for line in file("in.txt"):
...	data = line.rstrip('\n').split('\t')
...	data[3],data[4] = data[4],data[3]
...	outfile.write('\t'.join(data))
...	outfile.write('\n')

The python version can be made to be a full-fledged program if 
desired, that will take the two column-offsets (and perhaps even 
an optional delimiter) and swap the columns as desired.  Write 
back if you want this, and I can whip it up fairly quickly.

4) with Perl (it can be done, but I'm not a perl wonk, so some of 
the smarter Perl users on the list will have to help you here)

Hope this gives you some ideas to work with...

-tim







More information about the Blinux-list mailing list