I have a file (f1) that contains two columns; f1 looks as follows:
bob population1 sam population1 jen population2 amy population2 jim population3 bob population3 doc population4 allison population4 zoe population5 karla population5
In a different file (f2), I specify how I would like individuals in f1 to be sorted based on their population; f2 looks as follows:
population4 population1 population2 population5 population3
I am looking for the following outcome:
doc population4 allison population4 bob population1 sam population1 jen population2 amy population2 zoe population5 karla population5 jim population3 bob population3
Could anyone please give me advice on how to achieve this outcome?
Advertisement
Answer
You can loop over the lines from f2, extract the matching lines from f1 for each one:
while read s ; do grep "$s" f1 done < f2
Or, without a loop, some variation of
nl f2 | sed 's=([0-9]+)t(.*)=s/2/1 2/=' | sed -f- <(nl f1) | sort -nk3,3
i.e. number the lines in both files, replace the “populationX” with its corresponding number, then sort by the numbers.