Reputation:
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
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
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"
"\\y"
is needed to represent \y
- see gawk manual - Escape SequencesFNR==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