Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I swap the last column in a csv file to be the first column? + awk

Tags:

bash

sed

awk

How do I swap the last column in a csv file to be the first column?

I am thinking of using awk but not sure?

awk -F, '{print $1,$2}' filename

OR is sed a better option?

like image 200
HattrickNZ Avatar asked Dec 25 '22 20:12

HattrickNZ


1 Answers

For an arbitrary number of columns, you can do:

awk 'BEGIN {OFS=FS=",";} {temp=$NF; $NF = ""; sub(",$", ""); print temp, $0}' filename
  • OFS=FS="," sets the output and input field separators to comma.
  • temp = $NF saves the original contents of the last column in a variable.
  • $NF = '' empties the last column in the input.
  • sub(",$", "") gets rid of the extra comma left by that
  • print temp, $0 prints the saved last column followed by the rest of the input.

If you know how many columns there are, it's probably easier to do this using cut. If there are 9 columns, you can do:

cut -d, -f9,1-8 infile > outfile
like image 118
Barmar Avatar answered May 10 '23 23:05

Barmar