print line backwards - horizontally by field?

let's say you have

dog, cat, 1, 2, 3
reverse, 7, 9, i, tell, you

you want to print

3, 2, 1, cat, dog
you, tell, i, 9, 7, reverse

The delimiter is a comma. The number of commas in each line though is undetermined.

How would you do this using either regular UNIX or awk? I know the answer can't be that complex, but am having trouble thinking INSIDE the box.

echo dog, cat, 1, 2, 3 |awk '{for(i=NF;i>1;i--) printf $i OFS;print $1}' FS=, OFS=,
 3, 2, 1, cat,dog
1 Like

---------- Post updated at 04:14 AM ---------- Previous update was at 04:09 AM ----------

never mind my previous comment (which I edited). this does appear to work!

$ ruby -F"," -ane '$F[-1].chomp!; $F.reverse!; print "#{$F.join(",")}\n"' file
 3, 2, 1, cat,dog
 you, tell, i, 9, 7,reverse

Perl & Ruby:

perl -F, -lane'
  print join ",", reverse @F
  ' infile
ruby -F, -lane'
  print  $F.reverse.join ","
  ' infile

@radoulov, thanks for reminding. forgot about the -l switch.