bashawksed

How do I swap the last column in a csv file to be the first column? + 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?


Solution

  • For an arbitrary number of columns, you can do:

    awk 'BEGIN {OFS=FS=",";} {temp=$NF; $NF = ""; sub(",$", ""); print temp, $0}' filename
    

    If you know how many columns there are, it would be nice if we could do it like this:

    cut -d, -f9,1-8 infile > outfile
    

    But it doesn't work, see Rearrange columns using cut for the reason.