Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swap two columns - awk, sed, python, perl

Tags:

sed

awk

I've got data in a large file (280 columns wide, 7 million lines long!) and I need to swap the first two columns. I think I could do this with some kind of awk for loop, to print $2, $1, then a range to the end of the file - but I don't know how to do the range part, and I can't print $2, $1, $3...$280! Most of the column swap answers I've seen here are specific to small files with a manageable number of columns, so I need something that doesn't depend on specifying every column number.

The file is tab delimited:

Affy-id chr 0 pos NA06984 NA06985 NA06986 NA06989 
like image 269
Charley Farley Avatar asked Aug 15 '12 10:08

Charley Farley


People also ask

How do I swap two columns in awk?

open(fn_in, "r", encoding) as fp_in, \ codecs. open(fn_out, "w", encoding) as fp_out: for line in fp_in: # split into two columns and rest col1, col2, rest = line. split("\t", 2) # swap columns in output fp_out.

How do you switch columns in Linux?

How to switch columns in Linux. It's usually an CR-character. Meaning you have a file from the Windows/Dos world. Just run the dos2unix on that file to convert it.

Which command will swap positions of 1st and 3rd field in the output in Unix?

The -O option of join command allows us to choose the fields to display in a particular order using which we swap the fields.


2 Answers

You can do this by swapping values of the first two fields:

awk ' { t = $1; $1 = $2; $2 = t; print; } ' input_file 
like image 158
perreal Avatar answered Sep 27 '22 19:09

perreal


I tried the answer of perreal with cygwin on a windows system with a tab separated file. It didn't work, because the standard separator is space.

If you encounter the same problem, try this instead:

awk -F $'\t' ' { t = $1; $1 = $2; $2 = t; print; } ' OFS=$'\t' input_file 

Incoming separator is defined by -F $'\t' and the seperator for output by OFS=$'\t'.

awk -F $'\t' ' { t = $1; $1 = $2; $2 = t; print; } ' OFS=$'\t' input_file > output_file 
like image 24
emi-le Avatar answered Sep 27 '22 21:09

emi-le