仅按前两列对文件进行排序,并在列具有相同值的情况下保持输入顺序

时间:2018-11-28 22:33:25

标签: bash sorting columnsorting stability

我有一个输入文件,该行只希望按前两列进行排序。而且我想知道在bash中是否可以使用sort命令来完成此操作。

例如输入文件:

  

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/

我正在尝试

  

sort -b -k1,2 checkstart.txt

但是结果不是我期望的,因为它按照字母数字顺序对所有行进行排序:

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

我想要一个这样的结果文件:

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

1 个答案:

答案 0 :(得分:4)

您正在寻找一种stable排序算法。 sort提供了一个。您可以使用-s选项启用它。

$ 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