Sort strings in one file based on order in another file

Given file1:

13 abcd 5 facd 7 dcga 14 avsd 

and file2:

 7 x 5 c 14 a 13 i 

I would like to sort file1 based on the same order of the first column in file2 so that the output is as follows:

 7 dcga 5 facd 14 avsd 13 abcd 

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

+7
source share
2 answers

Use awk to put the line number from file2 as an extra column before file1 . Sort the result by this column. Then remove this prefix column

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

A simple solution

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

0
source

Source: https://habr.com/ru/post/987008/


All Articles