Use sort -k option / flag for advanced linux command line sorting

Sometimes you have a data file that needs sorting not just from left to right but by multiple values in the middle of each line. That is when you make use of the -k option / flag. 

Let’s look at the following data file; let’s call it test.txt. It starts with a timestamp in the German date format; meaning

Sorting all entries by date means I have to first sort by characters 7-10, then by characters 4-5 and lastly by 1-2. An additional hurdle is that we need numerical sorting for each of these groups rather than alphabetical sorting.

Sort by year

The first step is sorting by year. The sort option -k 1.7n looks for everything from character 7 until the first space and sorts it numerically.

If you want to have you command more concise you can add the range directly by using -k 1.7,1.10n instead of the implicit command above.

Sort by year and month

New we just have to add the addional sorting by month that gets executed after sorting by year has been done. Therefore we have to append the option -k 1.4,1.5n to our previous command. This means that we take the string from postion 4 to 5 and sort it numerically.

Sort by year, month and day

And finally we add a third sorting option that will be executed after everything has been sorted by year and month. We add the option -k 1.1,1.2n that says: take characters 1 to 2 and sort them also numerically.



(174 Posts)

20 years of coding and working as software engineer but I am still eager to learn more. I am very passionate when it comes to open source, Linux and Java. But I made my peace with Windows long ago to fully enjoy my PC gaming hobby. I have a soft spot for 90s electronic music and Babylon 5. In the evenings you will find me roaming the endless space in Warframe (IGN k05h).

One thought on “Use sort -k option / flag for advanced linux command line sorting

Comments are closed.