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.
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
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}
.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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With