Sorting lines in one file given the order in another file

前端 未结 2 1962
北海茫月
北海茫月 2021-02-09 02:46

Given a file1:

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

and a file2:

7 x
5 c
14 a
13 i

I would like to sort

相关标签:
2条回答
  • 2021-02-09 02:54

    Simple solution

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

    0 讨论(0)
  • 2021-02-09 03:10

    Use awk to put the line number from file2 as an extra column in front of file1. Sort the result by that column. Then remove that prefix column

    awk 'FNR == NR { lineno[$1] = NR; next}
         {print lineno[$1], $0;}' file2 file1 | sort -k 1,1n | cut -d' ' -f2-
    
    0 讨论(0)
提交回复
热议问题