views:

197

answers:

3

In a file I am reformatting, I would like to put the last column as the first and have the rest of the columns stay the same. I could do this easily in python, but thought I'd learn some awk this evening.

Here is an example:

(before)

polk_describes:1 diatribe_that:1 #label#:negative

(after)

#label#:negative polk_describes:1 diatribe_that:1

However, there are many more than 3 columns. In fact the column count varies.

Thanks,

SetJmp

+1  A: 

Here's one option:

% echo 'polk_describes:1 diatribe_that:1 #label#:negative' | \
  awk '{ print $NF " " substr($0, 1, length($0) - length($NF)) }'
#label#:negative polk_describes:1 diatribe_that:1
Nicholas Riley
A: 
  print $(NF), $1, $2, $3, $4  # etc. to the max number of columns

can also be written in a loop which is more elegant and precise, regarding the number of colums. (also see Nicholas Riley's trick in this post, to truncate the last field out of $0 and printing it at once).

mjv
+4  A: 

You can make assignments to fields, and thus clear them:

awk '{ lastfield = $NF; $NF = ""; print lastfield " " $0 }'
Dennis Williamson