user9259206
user9259206

Reputation:

awk to match keywords in two files

I am using the below command to match keyword from two files

awk 'FNR==NR{ids[$0]=$0;next}{for(id in ids){if($0 ~ /\yid\y/){print}}}' file1.txt file2.txt

Contents of file1.txt

work
run

file2.txt

I am running
I will run

desired output:

I will run

But I am not getting the desired output. What will be the correct syntax.

Upvotes: 1

Views: 220

Answers (2)

Akshay Hegde
Akshay Hegde

Reputation: 16997

For given inputs below awk also will work

awk 'FNR==NR{r=(r?r"|":"")$0;next}FNR==1{r="(^| )("r")( |$)"}$0~r' f1 f2

Test Results:

$ cat f1
work
run

$ cat f2
I am running
I will run

$ awk 'FNR==NR{r=(r?r"|":"")$0;next}FNR==1{r="(^| )("r")( |$)"}$0~r' f1 f2
I will run

Upvotes: 0

Sundeep
Sundeep

Reputation: 23697

$ awk 'FNR==NR{ids[$0]=$0;next}{for(id in ids){if($0 ~ "\\y"id"\\y"){print}}}' file1.txt file2.txt
I will run
  • /\yid\y/ means matching whole word id, not contents of id variable
  • "\\y"id"\\y" is concatenation of three strings - "\\y", contents of id variable and "\\y"
  • note that FNR==NR{ids[$0];next} will also work, no need to assign a value as only keys are needed


alternate solution using grep

$ grep -Ff file1.txt file2.txt
I am running
I will run
$ # -w option ensures to match only whole words
$ grep -wFf file1.txt file2.txt
I will run

use the -F option only if you need to match the strings literally

Upvotes: 1

Related Questions