compare two files and get the positions in third file in linux

93 views Asked by At

I need help with comparison of two files and get the positions in third file, both files will have the same fields but the order will be unsorted in 2nd file, third file will give the line number where the data is found.

eg. file1.txt
A
B
C
D

file2.txt
B
D
A
C

outputfileposition.txt
3
1
4
2

Any help appreciated, thanks in advance

2

There are 2 answers

0
blackSmith On

This will do the trick :

while read line
do
   grep -n $line file2.txt | grep -o ^[0-9]* >> outputfileposition.txt
done < file1.txt
3
123 On

In awk

awk 'FNR==NR{a[$0]=FNR;next}{print a[$0] > "outputfileposition.txt"}' file{2,1}.txt