LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Software (https://www.linuxquestions.org/questions/linux-software-2/)
-   -   strange behaviour of the sort command with key (https://www.linuxquestions.org/questions/linux-software-2/strange-behaviour-of-the-sort-command-with-key-4175600894/)

tshikose 03-02-2017 04:01 AM

strange behaviour of the sort command with key
 
Hi,

I have a strange behaviour with the sort command.
I do have a file with package names and corresponding rpm files separated by semi-colon.
Code:

$ cat packages.txt
httpd-tools;httpd-tools-2.4.6-45.el7.centos.x86_64.rpm
httpd;httpd-2.4.6-45.el7.centos.x86_64.rpm
httpd-manual;httpd-manual-2.4.6-45.el7.centos.noarch.rpm
httpd-devel;httpd-devel-2.4.6-45.el7.centos.x86_64.rpm

I want to sort it by package names, and have an output such as below.
Code:

httpd httpd-2.4.6-45.el7.centos.x86_64.rpm
httpd-devel httpd-devel-2.4.6-45.el7.centos.x86_64.rpm
httpd-manual httpd-manual-2.4.6-45.el7.centos.noarch.rpm
httpd-tools httpd-tools-2.4.6-45.el7.centos.x86_64.rpm

But the command below does not give me the expected output.
Code:

$ sort -k 1 -t ';' packages.txt
httpd-devel;httpd-devel-2.4.6-45.el7.centos.x86_64.rpm
httpd;httpd-2.4.6-45.el7.centos.x86_64.rpm
httpd-manual;httpd-manual-2.4.6-45.el7.centos.noarch.rpm
httpd-tools;httpd-tools-2.4.6-45.el7.centos.x86_64.rpm

I do not understand why httpd-devel is sorted before httpd.

If I isolate the package names then the sort command works as expected.
Code:

$ cut -f 1 -d ';' packages.txt | sort
httpd
httpd-devel
httpd-manual
httpd-tools

Any one with an explanation or a solution to my sorting need?

Turbocapitalist 03-02-2017 04:10 AM

If you have just -k 1 then it will start sorting at the first field and continue through the end of the line. It's rather buried in the manual, see KEYDEF, but if you tell it where to stop with -k 1,1 then it will sort as you expect.

Code:

$ sort -k 1,1 -t ';' packages.txt
You are thus telling it to sort only on the first field. However, that may not be what you want if you have more data to sort.

Code:

$ sort -k 1,1 -k 2 -t ';' packages.txt
That will tell it to first sort on the first field, but in cases of a tie sort on the rest of the line as well.

tshikose 03-02-2017 04:52 AM

Hi Turbocapitalist,

You are my saviour.
Yes, I read the man page top to bottom several times, without picking the real meaning and purpose on KEYDEF.

So definitively, sort -k 1,1 -t ';' packages.txt does the job for me.
I do not expect two different packages to have identical names.

I closed the thread.


All times are GMT -5. The time now is 10:23 AM.