How to sort lines in a file using bash
It is nice to know how to sort the contents of a file using bash. Let us take an example where we have a .csv
file with the records of employees as following:
emp_id;first_name;last_name;email;designation000002;Ash;Keys;[email protected];UX Designer000003;Sojiro;De Tenken;[email protected];Tester000001;Ashok;M A;[email protected];Web Developer
If we would like to sort the contents of this file for no reason, we can do it using sort
command.
$ sort ashokma.com/employees.csv000001;Ashok;M A;[email protected];Web Developer000002;Ash;Keys;[email protected];UX Designer000003;Sojiro;De Tenken;[email protected];Testeremp_id;first_name;last_name;email;designation
It is being sorted as expected but there is one little problem. The column names are at the bottom and we do not want that as it is not valid for database records processing. In order to keep the column names up top, we just have to supply the -r
option which is to reverse the output.
$ sort ashokma.com/employees.csvemp_id;first_name;last_name;email;designation000003;Sojiro;De Tenken;[email protected];Tester000002;Ash;Keys;[email protected];UX Designer000001;Ashok;M A;[email protected];Web Developer
As it only outputs the sorted values to console, we have to stream it back to the same file like:
sort ashokma.com/employees.csv > ashokma.com/employees.csv
I understand that it is in decending order but sorted ^_^ As an alternative, we can cut the columns line and paste it again once records are sorted!
Tip: Using the
-u
option you can keep only the unique records along with the sorting process.