Sort csv file with header by multiple columns

rcmliew

New Member
Joined
Aug 3, 2021
Messages
1
Reaction score
0
Credits
14
Hello,

I have a csv file with a header.

Example of file content:

Product,Color,Qty
Paper,White,5
Ruler,Yellow,3
Eraser,Blue,9
Ruler,Red,5
Pen,Blue,9
Ruler,Blue,9

Desired new file:
1) Header remains at the top
2) First sort by 1st column (by Product), then sort column 3 (by Qty) in descending order. Example output below:

Product,Color,Qty
Eraser,Blue,9
Paper,White,5
Pen,Blue,9
Ruler,Yellow,3
Ruler,Red,5
Ruler,Blue,9

If possible, i would like to use shell or perl. How can I do this?
 


Python is your friend.

That said, a quick Google search returned the following cli snip. I edited for your specific request, just change the filename placeholders.

Code:
(head -n 1 <input filename> && tail -n +2 <input filename> | sort) > <output filename>
 
Yup, that and in online courses, in college, etc...

We get homework questions fairly regularly. Rather than outright answer them, the general goal is to lead them to answer it themselves.

If it looks like some sort of practice exercise, it's probably homework. There's no problem with asking for homework help, though it's nice when they identify it as such.
 
Late to the party. And I haven’t tested it, because I’m nowhere near my pc ATM. But I think something like this should do the trick:
Bash:
sort -t"," -k1 -k3 /path/to/file > /path/to/sortedFile
Where /path/to/file is the path/filename of the file to sort. And /path/to/sortedFile is the path/filename for the sorted output file.
The -t option sets the comma , character as the field separator.
-k1 specifies that field 1 should be the primary sort key.
-k3 specifies that field 3 should be the secondary sort key.
 
2) First sort by 1st column (by Product), then sort column 3 (by Qty) in descending order. Example output below:

Product,Color,Qty
Eraser,Blue,9
Paper,White,5
Pen,Blue,9
Ruler,Yellow,3
Ruler,Red,5
Ruler,Blue,9
Doesn't the example show column 3 in ascending order? Is this a trick question? :oops:;)
 

Members online


Top