kami
kami

Reputation: 361

Sorting lines in a file using a specified order in another file

Given a 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 given in file2. Output should be:

n o p q
e f h
i j k
l m
a b c d

Basically, how can I add the file2 in front of file1 as a prefix column, and sort by that column, then remove the prefix column?

The answer here is a very close match, but doesn't exactly answer my question.

Upvotes: 3

Views: 128

Answers (1)

fedorqui
fedorqui

Reputation: 289605

paste is 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

Upvotes: 4

Related Questions