Thursday, November 22, 2007

Sort Nth Position of Nth Column of a File in Linux

How to sort file basically?
How to sort a file from the Nth column?
How to sort a file from Nth position of the Nth column?

A quick draw of achieving the above using the sort linux command.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# cat file.txt
6 4 8123
1 2 3789
4 6 9456
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Let us do a numerical sorting of the file using the basic usage of sort command.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# sort file.txt
1 2 3789
4 6 9456
6 4 8123
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Another file content sorting with columnar basis.

Sort the 3rd column of a text file
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# sort -nk 3 file.txt
1 2 3789
6 4 8123
4 6 9456
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Now, the sorting the Nth position of the Nth column of a file begins.

Sort the 3rd position of the 3rd column of a text file
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# sort -nk 3.3 file.txt
6 4 8123
4 6 9456
1 2 3789
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

How about sorting the 4th position from the 3rd column of a text file?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# sort -nk 3.4 file.txt
6 4 8123
4 6 9456
1 2 3789
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Good, you get the idea. Hope this helps and thanks for the visits!

This sort command was also included from my old blog entry from here and here.

0 comments:

Sign up for PayPal and start accepting credit card payments instantly.
ILoveTux - howtos and news | About | Contact | TOS | Policy