Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move column to last in awk

Tags:

bash

awk

cut

I would like to move a specified column (the 2nd) to the last column position. I have multiple large tab-delimited files containing variable numbers of columns and rows. But, column 2 in all needs to be last. Another way to put it is that I want the order to be 1,3-last,2.

From this:

Column1 Column2 Column3 ... Column W ColumnX
1 2 3 ... W X
a b c ... apples oranges

To this:

1 3 ... W X 2
a c ... apples oranges b

I'm newish to awk. From reading other threads, I've copied and tried various things like this with no success.

#doesn't reorder columns

cut -d $'\t' -f1,3-,2 file.in > file.out


#doesn't work and I don't really understand the for(i...) stuff copied from elsewhere:
cat file.in | awk -F'\t' '{print $1,for(i=3;i<=NF;++i) $i,$2}' > file.out

help?

Any pointers to threads/links that explain in simple educational terms what's going on with the for(i...) part would be appreciated as well. I get the gist, not the syntax.

like image 786
user3212388 Avatar asked Jan 20 '14 15:01

user3212388


2 Answers

With awk:

$ awk 'BEGIN{FS=OFS="\t"} {a=$2; for (i=2;i<NF; i++) $i=$(i+1); $NF=a}1' file
1       3       W       X       2
a       c       apples  oranges b

Which is the same as

awk 'BEGIN{FS=OFS="\t"} {a=$2; for (i=2;i<NF; i++) $i=$(i+1); $NF=a; print}' file

Explanation

  • BEGIN{FS=OFS="\t"} set input and output field separator as tab.
  • a=$2 store the 2nd value.
  • for (i=2;i<NF; i++) $i=$(i+1) move every value to the next one.
  • $NF=a set last value as the 2nd, which we stored.
  • 1 is a true condition that implies the default awk behaviour: {print $0}.
like image 184
fedorqui 'SO stop harming' Avatar answered Nov 02 '22 21:11

fedorqui 'SO stop harming'


With GNU awk for gensub():

$ cat file
Column1 Column2 Column3 ...     ColumnW ColumnX
1       2       3       ...     W       X
a       b       c       ...     apples  oranges

$ awk '{print gensub(/([\t][^\t]+)(.*)/,"\\2\\1","")}' file
Column1 Column3 ...     ColumnW ColumnX Column2
1       3       ...     W       X       2
a       c       ...     apples  oranges b
like image 36
Ed Morton Avatar answered Nov 02 '22 20:11

Ed Morton