【问题标题】:Linux sort command: keys with the same start but different length are not sorted in the same orderLinux排序命令:开始相同但长度不同的键不按相同顺序排序
【发布时间】:2013-08-27 01:45:28
【问题描述】:

我正在尝试对两个文件进行排序以加入它们。我排序的一些键非常相似,这似乎导致了问题。例如我有两个键是a1kea1k3-b3。我正在使用命令:

sort -nk1 file.txt -o file.txt

在一个文件中,它们以这种顺序出现,而在另一个文件中,它们以相反的顺序出现。当我尝试加入文件时,这会导致问题。

如何对这些文件进行排序,使它们的顺序相同?

谢谢

【问题讨论】:

    标签: linux sorting command-line-arguments


    【解决方案1】:

    不要使用“-n”选项,根据字符串数值比较。

    -n
    Compare according to arithmetic value an initial numeric string consisting of optional white
    space, an optional - sign, and zero or more digits, optionally followed by a decimal point and
    zero or more digits.
    

    您的键是字符串,而不是数字。

    相反,您应该这样做:

    sort -k1 file.txt -o file.txt
    

    其他信息:

    您可以看到sort 在使用-n 通过唯一排序时认为您的键相同:

    sort -un file
    

    您会看到a1k3-b3a1ke 被认为是相等的(因此只发出一个)。如果你这样做:

    sort -u file
    

    结果将同时包含a1k3-b3a1ke,这正是您想要的。

    【讨论】:

    • 在之前的文件编辑中,我对其中一个文件进行了独特的排序,这些键仍然存在。除了我想保留两者之外,有没有办法做到这一点并有统一的顺序?
    • @LeeAnn 我并不是建议您真正进行独特的排序。我只是建议您尝试查看a1k3-b3a1ke 在使用-n 选项时被认为是相同的键,但在省略它时不会。我会澄清我的答案。
    猜你喜欢
    • 1970-01-01
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    • 2021-03-24
    • 1970-01-01
    • 1970-01-01
    • 2021-10-26
    • 1970-01-01
    相关资源
    最近更新 更多