reverse order in a csv
With perl
, assuming the fields in your CSV don't have embedded commas, newlines, etc.:
perl -lpe '$_ = join ",", reverse split /,/' input.csv
You could use awk
:
awk 'BEGIN{
FS=OFS="," # set the field delimiter
}
{ # execute only on non empty line
for(i=NF;i>=1;i--) # loop through all elements
printf "%s", $i (i==1?ORS:OFS) # print the parameter together with the comma or newline
}' input.csv
CSV can't always be processed by simply splitting by lines and then commas, since fields may sometimes have commas or newlines themselves. To be able to include those characters, fields must be quoted.
This is a simple solution you can call from the shell that uses a proper csv parser:
ruby -r csv -e 'CSV.filter(&:reverse!)' input.csv
If you don't have ruby, this works with both python 2 and 3.
python -c $'import csv; import sys\nfor r in csv.reader(sys.stdin): r.reverse(); csv.writer(sys.stdout).writerow(r)' < input.csv > output.csv
Here it is in multiple lines:
python < input.csv > output.csv -c '
import csv
import sys
for r in csv.reader(sys.stdin):
r.reverse()
csv.writer(sys.stdout).writerow(r)
'
Here are some examples where this will work where solutions with simple comma splitting won't work:
input.csv
1,"2,3"
output.csv
"2,3",1
input.csv
1,"
2"
output.csv
"
2",1