How to Sort Files by Multicolumn

My file has 3 columns and I want to sort the data in the file by column 1 (DESC), column 2(ASC) and save the result to another file. How can I do that?

3

1 Answer

sort has the option to sort by multiple columns, do:

sort -k1,1 -k2,2 file.txt 

The above will sort the file first by whitespace separated column 1, then by column 2.

You can also set other delimiter than any whitespace by the -t option, e.g. setting , as the delimiter:

sort -t ',' -k1,1 -k2,2 file.txt

Check man sort.

Your Answer

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

James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.

Share this article
Twitter Facebook Pinterest