Sort lines in a file using a specified order in another file
Given file1
a b c d
e f h
n o p q
i j k
l m
and another file2
3 1 0 1 2
I would like to sort file1 in the order listed in file2. The output should be:
n o p q
e f h
i j k
l m
a b c d
Basically, how can I add file2 before file 1 as a prefix column and sort it by that column, then remove the prefix column?
The answer here is a very close match, but doesn't exactly answer my question.
+3
source to share
1 answer
paste
- your friend:
paste f2 f1 | sort | cut -d$'\t' -f2-
In steps:
$ paste f2 f1 # join files
3 a b c d
1 e f h
0 n o p q
1 i j k
2 l m
$ paste f2 f1 | sort # sort them
0 n o p q
1 e f h
1 i j k
2 l m
3 a b c d
$ paste f2 f1 | sort | cut -d$'\t' -f2- # remove 1st column
n o p q
e f h
i j k
l m
a b c d
+4
source to share