How do I replace the first column in a csv file with the first column? + awk

How do I change the last column in the csv file to the first column?

I'm thinking about using awk but not sure?

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

OR is there a sed

better option?

+3


source to share


5 answers


For an arbitrary number of columns, you can:

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

      

  • OFS=FS=","

    sets the output and input field separators to commas.
  • temp = $NF

    stores the original content of the last column in a variable.
  • $NF = ''

    empties the last column of the input.
  • sub(",$", "")

    gets rid of the extra comma left by this
  • print temp, $0

    prints the last column saved, followed by the rest of the input.


If you know how many columns there are, it might be easier to do this with cut

. If there are 9 columns, you can do:

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

      

+3


source


Using gawk and gensub

awk '$0=gensub(/(.*),(.*)/,"\\2,\\1","1")'

      


Input

1,2,3,4,5,6
a,b,c,d,e,f

      

Output

6,1,2,3,4,5
f,a,b,c,d,e

      


If you want to change them



awk '$0=gensub(/([^,]+),(.*),(.*)/,"\\3,\\2,\\1","1")'

      

Input

1,2,3,4,5,6
a,b,c,d,e,f

      

Output

6,2,3,4,5,1
f,b,c,d,e,a

      


Same thing in sed

sed -r 's/([^,]+),(.*),(.*)/\3,\2,\1/'

      

+2


source


sed 's/\(.*\),\([^,]*\)/\2,\1/' YourFile

      

In this case, sed is fully compatible.

Optimization from @JID using the fact that there is ,

no ending and is based on the group order behavior

sed 's/\(.*\),\(.*\)/\2,\1/' YourFile

      

+2


source


I would go with the correct CSV parser. Ruby comes with one

Do you want to exchange the first and last fields?
Or do you want to move the last field forward?

If the latter:

ruby -rcsv -ne '
  row = CSV.parse_line($_.chomp!)
  row.unshift(row.pop)
  # to exchange first and last fields: row[0],row[-1] = row[-1],row[0]
  puts CSV.generate_line(row)
' <<END
a,b,c
d,e,f
g,h,"""Just drive,"" she said"
END

      

c,a,b
f,d,e
"""Just drive,"" she said",g,h

      

(this ignores fields containing newlines)

+1


source


With GNU awk and some others, you need the following:

$ echo 'a,b,c' | awk 'BEGIN{FS=OFS=","} {$0=$NF FS $0; NF--} 1'
c,a,b

      

otherwise this will work with any awk:

$ echo 'a,b,c' | awk 'BEGIN{FS=OFS=","} {$0=$NF FS $0; sub(/,[^,]*$/,"")} 1'
c,a,b

      

+1


source







All Articles