0

I read through the sort manual but I feel like I'm missing something.

Source File

Here is the CSV file I'm trying to sort:

$ cat SAMPLE.CSV 
compid,active,tagno
-2147483646,1,"1"
-2147483645,0,"10000"
-2147483644,0,"1002"
-2147483127,1,"76245.1"
-2147483126,1,"76245.2"
-2147468087,1,"76245"

Desired Result

I'm trying to sort by the third (last) column, also known as the tagno column. The desired result should look like this:

compid,active,tagno
-2147483646,1,"1"
-2147483644,0,"1002"
-2147483645,0,"10000"
-2147468087,1,"76245"
-2147483127,1,"76245.1"
-2147483126,1,"76245.2"

Vain Attempts

By all accounts, the following command should do exactly what I want:

$ sort SAMPLE.CSV -n -k 3 -t ','
-2147468087,1,"76245"
-2147483126,1,"76245.2"
-2147483127,1,"76245.1"
-2147483644,0,"1002"
-2147483645,0,"10000"
-2147483646,1,"1"
compid,active,tagno

I even tried with the "general-numeric-sort" option:

$ sort SAMPLE.CSV -g -k 3 -t ','
-2147468087,1,"76245"
-2147483126,1,"76245.2"
-2147483127,1,"76245.1"
-2147483644,0,"1002"
-2147483645,0,"10000"
-2147483646,1,"1"
compid,active,tagno

This the first time using sort so I feel like I'm missing something fundamental here.

sort version

$ sort --version
2.3-Apple (99)

Help please?

1

The default field separator in sort is non-blank to blank transition. You need a different separator here: a doublequote.

sort -t'"' -k2n SAMPLE.CSV

You are then sorting by the 2nd column. Fortunately, the second column is empty in the header line, so it comes first.

| improve this answer | |
  • First of all, you're a genius. Secondly, wat? I thought I would have to specify a comma as the field separator, like -t ','? – Joshua Pinter Mar 24 '18 at 23:01
  • A number must start with a digit (or - or .), not doublequote, so comma doesn't help here. – choroba Mar 24 '18 at 23:07
  • Gotcha. I have a follow-up question. Your command is sorting numbers with a letter in it oddly, like so: -2147466194,1,"1361B.2"\n -2147466195,1,"1361B.1"\n -2147466196,1,"1361B" Any idea how to fix those? (for clarity, I'll toss this in the original question as an edit) – Joshua Pinter Mar 24 '18 at 23:26
  • Please, don't. To ask a new question, create a new question. – choroba Mar 24 '18 at 23:30
  • You're right. I created another question and answered it myself over here: superuser.com/questions/1307618/… Thanks again for your help! – Joshua Pinter Mar 24 '18 at 23:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.