How do I replace the first column in a csv file with the first column? + awk
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 to share
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
user4453924
source
to share
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 to share