Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting lines in one file given the order in another file

Tags:

file

bash

sorting

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 file1 considering the same order of the first column in file2, so that the output should be:

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

Is it possible to do this in bash or should I use some "higher" language like python?

like image 490
no_name Avatar asked May 12 '15 01:05

no_name


1 Answers

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-
like image 140
Barmar Avatar answered Nov 15 '22 17:11

Barmar