bashsortingcolumnsortingstability

Sort file by only first two columns and keep the input order in case the columns have same values


I have an input file which lines I'd like sort by only 2 first columns. And I'd like to know if there is some way to do it with sort command in bash.

Ex. Input File:

cat checkstart.txt

dev XCUBOBS149 /etc/init.d/DSEngine_srv
dev XCUBOBS150 /etc/init.d/DSEngine_srv
dev XCUBOBS149 NO_LINKS_TO_STARTSCRIPTS
dev XCUBOBS149 ufabric:x:46000:46000::/home/ufabric:/bin/bash
dev XCUBOBS149 export JAVA_HOME=/soft/jdk/jdk1.7.0_79/

I'm trying with

sort -b -k1,2 checkstart.txt

but result is not what I'm expecting because it's sorting all the lines by alphanumerical order:

dev XCUBOBS149 /etc/init.d/DSEngine_srv
dev XCUBOBS149 export JAVA_HOME=/soft/jdk/jdk1.7.0_79/
dev XCUBOBS149 NO_LINKS_TO_STARTSCRIPTS
dev XCUBOBS149 ufabric:x:46000:46000::/home/ufabric:/bin/bash
dev XCUBOBS150 /etc/init.d/DSEngine_srv

I'd like get a result file like this:

dev XCUBOBS149 /etc/init.d/DSEngine_srv
dev XCUBOBS149 NO_LINKS_TO_STARTSCRIPTS
dev XCUBOBS149 ufabric:x:46000:46000::/home/ufabric:/bin/bash
dev XCUBOBS149 export JAVA_HOME=/soft/jdk/jdk1.7.0_79/
dev XCUBOBS150 /etc/init.d/DSEngine_srv

Solution

  • You are looking for a stable sort algorithm. sort provides one. You can enable it with the -s option.

    $ sort -s -k1,2 checkstart.txt
    dev XCUBOBS149 /etc/init.d/DSEngine_srv
    dev XCUBOBS149 NO_LINKS_TO_STARTSCRIPTS
    dev XCUBOBS149 ufabric:x:46000:46000::/home/ufabric:/bin/bash
    dev XCUBOBS149 export JAVA_HOME=/soft/jdk/jdk1.7.0_79/
    dev XCUBOBS150 /etc/init.d/DSEngine_srv