【问题标题】:Sorting lines in one file given the order in another file给定另一个文件中的顺序,对一个文件中的行进行排序
【发布时间】:2015-05-12 01:21:35
【问题描述】:

给定一个文件1:

13 a b c d
5 f a c d
7 d c g a
14 a v s d

还有一个文件2:

7 x
5 c
14 a
13 i

我想考虑 file2 中第一列的相同顺序对 file1 进行排序,因此输出应该是:

7 d c g a
5 f a c d
14 a v s d
13 a b c d

是否可以在 bash 中执行此操作,或者我应该使用一些“高级”语言,例如 python?

【问题讨论】:

    标签: bash file sorting


    【解决方案1】:

    使用awkfile2 中的行号作为额外列放在file1 前面。按该列对结果进行排序。然后删除该前缀列

    awk 'FNR == NR { lineno[$1] = NR; next}
         {print lineno[$1], $0;}' file2 file1 | sort -k 1,1n | cut -d' ' -f2-
    

    【讨论】:

      【解决方案2】:

      简单的解决方案

      for S in $(cat file2 | awk '{print $1}'); do grep $S file1; done

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-07-16
        • 1970-01-01
        • 2012-02-26
        • 1970-01-01
        • 1970-01-01
        • 2019-10-10
        • 2018-11-28
        • 1970-01-01
        相关资源
        最近更新 更多