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?
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 thatprint 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
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