gamerounet gamerounet - 7 months ago 11
Bash Question

find same value in 2 differents column from differents files

I got 2 files:

file1.txt:

1 A bla 9232
1 B tesfs 3049
1 C blof 4054
2 D dkeeez 3049
2 E eor 4042
3 F foaer 4024


file2.txt:

A
B
E


Expected output, file3.txt:

1 A bla 9232
1 B tesfs 3049
2 E eor 4042


The output is simply the line from the file1 that contains the same value in column 2 than in the file2.

In file2.txt, each line is unique, but you can have :

A
AA
AAee
B
...


I tried to used grep -Ff file2.txt file1.txt but there's still line in file3.txt that doesn't exist in file2.txt
The solution can be in line or in a shell script, I tried to use "awk" and shell script, without result...

Answer

You can use awk command:

awk 'FNR==NR{a[$1]; next} $2 in a' file2.txt file1.txt

In the first iteration we store all values from file2.txt into an array a. In the 2nd step white iterating file1.txt we check if column 2 is in array a and print it.

Output:

1 A bla 9232
1 B tesfs 3049
2 E eor 4042