Reputation: 53
I would like to recursively search a file (file1) using search terms from a list (file2). File 1 contains a long list of items separated by commas in one column. I would like to create a new file (file3) listing the search term and the line containing the search term. Can I use grep/sed/awk to do this?
file 1
A, 1, 2, 3
B, 4, 5, 6
C, 7, 8, 9
file 2
A
B
C
D
Desired file 3
A A, 1, 2, 3
B B, 4, 5, 6
C C, 7, 8, 9
Upvotes: 0
Views: 291
Reputation: 3355
Using awk to save to file3 use this code :-
awk -F"," 'NR==FNR{k[$0];next}
{for(i=1;i<=NF;i++)if($i in k){print $i,$0;break}}' file2 file1 > file3
The contents will be saved to file3 . use cat file3
to display contents of file3.
output of cat file3
A A, 1, 2, 3
B B, 4, 5, 6
C C, 7, 8, 9
Upvotes: 1
Reputation: 195229
This awk one-liner should help:
awk -F"," 'NR==FNR{k[$0];next}
{for(i=1;i<=NF;i++)if($i in k){print $i,$0;break}}' file2 file1
Upvotes: 1